Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add solutions to lc problem: No.393 #3016

Merged
merged 2 commits into from
Jun 3, 2024
Merged

feat: add solutions to lc problem: No.393 #3016

merged 2 commits into from
Jun 3, 2024

Conversation

yanglbme
Copy link
Member

@yanglbme yanglbme commented Jun 3, 2024

No.0393.UTF-8 Validation

@idoocs idoocs added cpp Issues or Pull requests relate to .cpp code core team Issues or pull requests from core team go Issues or Pull requests relate to .go code java Issues or Pull requests relate to .java code md Issues or Pull requests relate to .md files py Issues or Pull requests relate to .py code ts Issues or Pull requests relate to .ts code labels Jun 3, 2024
thinkasany
thinkasany previously approved these changes Jun 3, 2024
@thinkasany
Copy link
Member

其实有点魔法字符串了
copilot 是这样子建议的,不过处于做题的话,那样子应该问题也不大,但是 js还是都用上 === 三等吧

function isSingleByte(v: number): boolean {
  return (v >> 7) === 0;
}

function isContinuationByte(v: number): boolean {
  return (v >> 6) === 0b10;
}

function getContinuationBytesCount(v: number): number {
  if ((v >> 5) === 0b110) return 1;
  if ((v >> 4) === 0b1110) return 2;
  if ((v >> 3) === 0b11110) return 3;
  return -1;
}

function validUtf8(data: number[]): boolean {
  let cnt = 0;
  for (const v of data) {
    if (cnt > 0) {
      if (!isContinuationByte(v)) {
        return false;
      }
      --cnt;
    } else if (isSingleByte(v)) {
      cnt = 0;
    } else {
      const newCnt = getContinuationBytesCount(v);
      if (newCnt === -1) {
        return false;
      }
      cnt = newCnt;
    }
  }
  return cnt === 0;
}

@thinkasany thinkasany merged commit 2d20e9d into main Jun 3, 2024
6 checks passed
@thinkasany thinkasany deleted the dev branch June 3, 2024 12:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
core team Issues or pull requests from core team cpp Issues or Pull requests relate to .cpp code go Issues or Pull requests relate to .go code java Issues or Pull requests relate to .java code md Issues or Pull requests relate to .md files py Issues or Pull requests relate to .py code ts Issues or Pull requests relate to .ts code
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants