-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathUTF-8 Validation.py
46 lines (40 loc) · 1.14 KB
/
UTF-8 Validation.py
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from typing import List
class Solution:
"""
Time: O(n)
Memory: O(1)
"""
BITS = [
0b00000000,
0b00000001,
0b00000010,
0b00000100,
0b00001000,
0b00010000,
0b00100000,
0b01000000,
0b10000000,
]
def validUtf8(self, data: List[int]) -> bool:
trailing_bytes = 0
for byte in data:
if trailing_bytes < 0:
return False
elif trailing_bytes > 0:
if not (byte & self.BITS[8]) or (byte & self.BITS[7]):
return False
trailing_bytes -= 1
else:
if not (byte & self.BITS[8]):
continue
elif not (byte & self.BITS[7]):
return False
elif not (byte & self.BITS[6]):
trailing_bytes = 1
elif not (byte & self.BITS[5]):
trailing_bytes = 2
elif not (byte & self.BITS[4]):
trailing_bytes = 3
else:
return False
return not trailing_bytes