forked from kaidul/LeetCode_problems_solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UTF-8_Validation.cpp
32 lines (32 loc) · 917 Bytes
/
UTF-8_Validation.cpp
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
class Solution {
const int MSB = 7;
public:
bool validUtf8(vector<int>& data) {
int i = 0, n = (int)data.size();
while(i < n) {
int nbyte = 0;
for(int k = 0; k < 4 and (data[i] & (1 << (MSB - k))); k++) {
nbyte++;
}
if(nbyte == 1) {
return false;
}
if(nbyte == 0) nbyte++;
if(nbyte > 1 and (bool)(data[i] & (1 << (MSB - nbyte))) ) {
return false;
}
if(i + nbyte - 1 >= n) {
return false;
}
for(int k = 1; k < nbyte; k++) {
bool on = data[i + k] & (1 << MSB);
bool off = data[i + k] & (1 << (MSB - 1));
if(!on or off) {
return false;
}
}
i += nbyte;
}
return true;
}
};