-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUTF-8Validation393.cpp
More file actions
100 lines (99 loc) · 2.43 KB
/
UTF-8Validation393.cpp
File metadata and controls
100 lines (99 loc) · 2.43 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
//easy understanding solution
class Solution {
public:
bool validUtf8(vector<int>& data) {
/*cout << data.size() <<endl;
for (int i : data) {
for (int j = 7; j > -1; j--) {
if ((i>>j)&1)cout << "1";
else cout <<"0";
}
cout << endl;
}*/
int count = 0;
for(int d:data){
if(count == 0){
if((d >> 5) == 0b110) count = 1;
else if((d >> 4) == 0b1110) count = 2;
else if((d >> 3) == 0b11110) count = 3;
else if((d >> 7) == 1) return false;
} else {
if((d>>6) != 0b10) return false;
else count--;
}
}
return count == 0;
}
};
//my solution
class Solution {
public:
bool validUtf8(vector<int>& data) {
int leading = 0, count = 0;
for (int i = 0; i < data.size(); i++) {
count = 0;
for (int j = 7; j > -1; j--) {
if( (data[i]>>j) &1 ) {
count++;
} else {
break;
}
}
//cout << count <<" , ";
if (count > 4) return false;
if (count == 1) {
if (leading) {
leading--;
} else {
return false;
}
} else if (count == 0) {
if (leading) return false;
leading = 0;
} else {
if (leading == 0) leading = count-1;
else return false;
}
}
if(leading) return false;
return true;
}
};
//the fatest solution
auto desyncio = []()
{
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
bool validUtf8(vector<int>& data) {
int n_bytes = 0;
for (int num : data)
{
if (n_bytes == 0)
{
int mask = 1 << 7;
while (num & mask)
{
++n_bytes;
mask >>= 1;
}
if (n_bytes == 0)
continue;
if (n_bytes == 1 || n_bytes > 4)
return false;
}
else
{
int mask1 = 1 << 7, mask2 = 1 << 6;
if (!(num & mask1) || (mask2 & num))
return false;
//--n_bytes;
}
--n_bytes;
}
return n_bytes == 0;
}
};