Skip to content

Commit 5160187

Browse files
author
openset
committed
Add: UTF-8 Validation
1 parent c17cc27 commit 5160187

File tree

3 files changed

+62
-2
lines changed

3 files changed

+62
-2
lines changed

internal/leetcode/problems_status.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ var problemStatus = map[int]bool{
3737
50: true,
3838
53: true,
3939
58: true,
40+
65: true,
4041
66: true,
4142
67: true,
4243
69: true,
@@ -97,6 +98,7 @@ var problemStatus = map[int]bool{
9798
371: true,
9899
383: true,
99100
387: true,
101+
393: true,
100102
412: true,
101103
413: true,
102104
414: true,
Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,21 @@
1-
package utf_8_validation
1+
package problem_393
2+
3+
func validUtf8(data []int) bool {
4+
u := 0
5+
for _, v := range data {
6+
if u == 0 && v>>7 == 0 { // 0b0
7+
u = 0
8+
} else if u == 0 && v>>5 == 6 { // 0b110
9+
u = 1
10+
} else if u == 0 && v>>4 == 14 { // 0b1110
11+
u = 2
12+
} else if u == 0 && v>>3 == 30 { // 0b11110
13+
u = 3
14+
} else if u > 0 && v>>6 == 2 { // 0b10
15+
u--
16+
} else {
17+
return false
18+
}
19+
}
20+
return u == 0
21+
}
Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,39 @@
1-
package utf_8_validation
1+
package problem_393
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input []int
7+
expected bool
8+
}
9+
10+
func TestValidUtf8(t *testing.T) {
11+
tests := [...]caseType{
12+
{
13+
input: []int{197},
14+
expected: false,
15+
},
16+
{
17+
input: []int{197, 130, 1},
18+
expected: true,
19+
},
20+
{
21+
input: []int{235, 140, 4},
22+
expected: false,
23+
},
24+
{
25+
input: []int{248},
26+
expected: false,
27+
},
28+
{
29+
input: []int{194, 155, 231, 184, 185, 246, 176, 131, 161, 222, 174, 227, 162, 134, 241, 154, 168, 185, 218, 178, 229, 187, 139, 246, 178, 187, 139, 204, 146, 225, 148, 179, 245, 139, 172, 134, 193, 156, 233, 131, 154, 240, 166, 188, 190, 216, 150, 230, 145, 144, 240, 167, 140, 163, 221, 190, 238, 168, 139, 241, 154, 159, 164, 199, 170, 224, 173, 140, 244, 182, 143, 134, 206, 181, 227, 172, 141, 241, 146, 159, 170, 202, 134, 230, 142, 163, 244, 172, 140, 191},
30+
expected: true,
31+
},
32+
}
33+
for _, tc := range tests {
34+
output := validUtf8(tc.input)
35+
if output != tc.expected {
36+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
37+
}
38+
}
39+
}

0 commit comments

Comments
 (0)