A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:

For 1-byte character, the first bit is a 0, followed by its unicode code.
For n-bytes character, the first n-bits are all one's, the n+1 bit is 0, followed by n-1 bytes with most significant 2 bits being 10.

This is how the UTF-8 encoding would work:

   Char. number range  |        UTF-8 octet sequence
      (hexadecimal)    |              (binary)
   --------------------+---------------------------------------------
   0000 0000-0000 007F | 0xxxxxxx
   0000 0080-0000 07FF | 110xxxxx 10xxxxxx
   0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
   0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx


Given an array of integers representing the data, return whether it is a valid utf-8 encoding.


Note:
The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data.



Example 1:

data = [197, 130, 1], which represents the octet sequence: 11000101 10000010 00000001.

Return true.
It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.




Example 2:

data = [235, 140, 4], which represented the octet sequence: 11101011 10001100 00000100.

Return false.
The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character.
The next byte is a continuation byte which starts with 10 and that's correct.
But the second continuation byte does not start with 10, so it is invalid.

Difficulty: interview

Starter code:

class Solution:
    def validUtf8(self, data: List[int]) -> bool:
        

Solutions:
class Solution:
     def validUtf8(self, data):
         """
         :type data: List[int]
         :rtype: bool
         """
         count=0
         for x in data:
             if count==0:
                 if x>>5==0b110:
                     count=1
                 elif x>>4==0b1110:
                     count=2
                 elif x>>3==0b11110:
                     count=3
                 elif x>>7==1:
                     return False
             else:
                 if x>>6!=0b10:
                     return False
                 count-=1
         return count==0
         
         
 #         class Solution {
 # public:
 #     bool validUtf8(vector<int>& data) {
 #         int cnt = 0;
 #         for (int d : data) {
 #             if (cnt == 0) {
 #                 if ((d >> 5) == 0b110) cnt = 1;
 #                 else if ((d >> 4) == 0b1110) cnt = 2;
 #                 else if ((d >> 3) == 0b11110) cnt = 3;
 #                 else if (d >> 7) return false;
 #             } else {
 #                 if ((d >> 6) != 0b10) return false;
 #                 --cnt;
 #             }
 #         }
 #         return cnt == 0;
 #     }
 # };


class Solution:
     def validUtf8(self, data):
         """
         :type data: List[int]
         :rtype: bool
         """
         count = 0
         for d in data:
             if count == 0:
                 if d >> 5 == 0b110:
                     count = 1
                 elif d >> 4 == 0b1110:
                     count = 2
                 elif d >> 3 == 0b11110:
                     count = 3
                 elif d >> 7 != 0:
                     return False
             else:
                 if d >> 6 == 0b10:
                     count -= 1
                 else:
                     return False
         return count == 0

class Solution:
     def countLeadingOne(self, w):
         if w[0] == '0':
             return 1
         elif w[0:3] =="110":
             return 2
         elif w[0:4] == '1110':
             return 3
         elif w[0:5] == '11110':
             return 4
         else:
             return -1
         
     def checkStartWith10(self, L,l):
         #print(L, l)
         if len(L)!=l:
             return False
         
         for w in L:
             if w.startswith('10') == False:
                 return False
         
         return True
     
     def validUtf8(self, data):
         """
         :type data: List[int]
         :rtype: bool
         """
         A= []
         for d in data:
             A.append(format(d, '08b'))
         
         i = 0
       
         while i < len(A):
             l = self.countLeadingOne(A[i])
             if l == -1:
                 return False
 
             if l > 1:
                 if self.checkStartWith10(A[i+1:i+l], l-1) == False:
                     return False
             
             i+=l
             
         return True
         


class Solution:
     def validUtf8(self, data):
         n = len(data)
         check10 = 0
         for byte in data:
             if check10:
                 if byte & 0b11000000 != 0b10000000:
                     return False
                 check10 -= 1
             elif byte & 0b11111000 == 0b11110000:
                 check10 = 3
             elif byte & 0b11110000 == 0b11100000:
                 check10 = 2
             elif byte & 0b11100000 == 0b11000000:
                 check10 = 1
             elif byte & 0b10000000 == 0:
                 continue
             else:
                 return False
         return check10 == 0
 


class Solution:
     def validUtf8(self, data):
         """
         :type data: List[int]
         :rtype: bool
         """
         count = 0
         for num in data:
             if count == 0:
                 if (num >> 5) == 0b110: count = 1
                 elif (num >> 4) == 0b1110: count = 2
                 elif (num >> 3) == 0b11110: count = 3
                 elif (num >> 7): return False
             else:
                 if (num >> 6) != 0b10: return False
                 count -= 1
         return count == 0


class Solution:
     def check(self, nums, start, size):
         for i in range(start + 1, start + size + 1):
             if i >= len(nums) or (nums[i] >> 6) != 0b10: return False
         return True
 
     def validUtf8(self, nums, start=0):
         """
         :type data: List[int]
         :rtype: bool
         """
         while start < len(nums):
             first = nums[start]
             if   (first >> 3) == 0b11110 and self.check(nums, start, 3): start += 4
             elif (first >> 4) == 0b1110  and self.check(nums, start, 2): start += 3
             elif (first >> 5) == 0b110   and self.check(nums, start, 1): start += 2
             elif (first >> 7) == 0:                                 start += 1
             else:                                                   return False
         return True


class Solution:
     def validUtf8(self, data):
         """
         :type data: List[int]
         :rtype: bool
         """
         def numOfFollowingBytes(num):
             if 0 <= num <= 127:
                 return 0
             elif 192 <= num <= 223:
                 return 1
             elif 224 <= num <= 239:
                 return 2
             elif 240 <= num <= 247:
                 return 3
             else:
                 return -1
         
         def isFollowingByte(num):
             return 128 <= num <= 191
         
         if not data:
             return False
         
         i, n = 0, len(data)
         while i < n:
             bytesToFollow = numOfFollowingBytes(data[i])
             if bytesToFollow == -1:
                 return False
             
             i += 1
             if i + bytesToFollow > n:
                 return False
             
             for _ in range(bytesToFollow):
                 if not isFollowingByte(data[i]):
                     return False
                 i += 1
         
         return True

class Solution:
     def validUtf8(self, data):
         """
         :type data: List[int]
         :rtype: bool
         """
         cont = 0
         for n in data:
             s=format(n, '08b')
             if cont > 0:
                 if s[:2] == '10':
                     cont -= 1
                     continue
                 return False
             if s[0] == '0':
                 continue
             if s[:3] == '110':
                 cont = 1
                 continue
             if s[:4] == '1110':
                 cont = 2
                 continue
             if s[:5] == '11110':
                 cont = 3
                 continue
             return False
         return cont == 0


class Solution:
     def validUtf8(self, data):
         seqs = len(data)
         idx = 0
         while idx < seqs:
             number = data[idx] & 255 | 256  # XXX: make it as 0b1xxxxxxxx
             seq = bin(number)[3:]
             bits = len(seq.split('0')[0])
             
             if idx + bits > seqs:
                 return False
             elif bits > 4:
                 # maximum 4 bytes
                 # 0b11111111
                 return False
             elif bits == 0:
                 # 1 byte UTF-8
                 idx += 1
             elif bits == 1:
                 # 0b10000000
                 return False
             else:
                 for i in range(1, bits):
                     num = data[idx + i] & 255
                     if num >= int('11000000', 2) or num < int('10000000', 2):
                         return False
                 idx += bits
 
         return True


class Solution:
     def validUtf8(self, data):
         seqs = len(data)
         idx = 0
         while idx < seqs:
             number = data[idx] & 255 | 256  # XXX: make it as 0b1xxxxxxxx
             seq = bin(number)[3:]
             bits = len(seq.split('0')[0])
             
             if idx + bits > seqs:
                 return False
             elif bits > 4:
                 # maximum 4 bytes
                 # 0b11111111
                 return False
             elif bits == 1:
                 # 0b10000000
                 return False
             elif bits == 0:
                 # 1 byte UTF-8
                 idx += 1
             else:
                 for i in range(1, bits):
                     num = data[idx + i] & 255
                     if num >= int('11000000', 2) or num < int('10000000', 2):
                         return False
                 idx += bits
 
         return True


class Solution:
     def validUtf8(self, data):
         """
         :type data: List[int]
         :rtype: bool
         """
         current = 0
         for byte in data:
             b = "{0:08b}".format(byte)
             if current == 0:
                 cnt = 0
                 for i in b:
                     if i == '0':
                         break
                     else:
                         cnt += 1
                 if cnt == 1 or cnt > 4:
                     return False
                 if cnt > 0:
                     current = cnt - 1
                 else:
                     current = 0
             else:
                 if b[0:2] != '10':
                     return False
                 current -= 1
         if current > 0:
             return False
         return True