Skip to content

393. UTF-8 Validation 👎

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
 public:
  bool validUtf8(vector<int>& data) {
    int followedBytes = 0;

    for (const int d : data)
      if (followedBytes == 0) {
        if ((d >> 3) == 0b11110)
          followedBytes = 3;
        else if ((d >> 4) == 0b1110)
          followedBytes = 2;
        else if ((d >> 5) == 0b110)
          followedBytes = 1;
        else if ((d >> 7) == 0b0)
          followedBytes = 0;
        else
          return false;
      } else {
        if ((d >> 6) != 0b10)
          return false;
        --followedBytes;
      }

    return followedBytes == 0;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
  public boolean validUtf8(int[] data) {
    int followedBytes = 0;

    for (final int d : data)
      if (followedBytes == 0) {
        if ((d >> 3) == 0b11110)
          followedBytes = 3;
        else if ((d >> 4) == 0b1110)
          followedBytes = 2;
        else if ((d >> 5) == 0b110)
          followedBytes = 1;
        else if ((d >> 7) == 0b0)
          followedBytes = 0;
        else
          return false;
      } else {
        if ((d >> 6) != 0b10)
          return false;
        --followedBytes;
      }

    return followedBytes == 0;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
  def validUtf8(self, data: list[int]) -> bool:
    followedBytes = 0

    for d in data:
      if followedBytes == 0:
        if (d >> 3) == 0b11110:
          followedBytes = 3
        elif (d >> 4) == 0b1110:
          followedBytes = 2
        elif (d >> 5) == 0b110:
          followedBytes = 1
        elif (d >> 7) == 0b0:
          followedBytes = 0
        else:
          return False
      else:
        if (d >> 6) != 0b10:
          return False
        followedBytes -= 1

    return followedBytes == 0