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
| // @Title: UTF-8 编码验证 (UTF-8 Validation)
// @Author: 15816537946@163.com
// @Date: 2022-03-13 10:03:03
// @Runtime: 8 ms
// @Memory: 5 MB
const mask1, mask2 = 1 << 7, 1<<7 | 1<<6
func getBytes(num int) int {
if num&mask1 == 0 {
return 1
}
n := 0
for mask := mask1; num&mask != 0; mask >>= 1 {
n++
if n > 4 {
return -1
}
}
if n >= 2 {
return n
}
return -1
}
func validUtf8(data []int) bool {
for index, m := 0, len(data); index < m; {
n := getBytes(data[index])
if n < 0 || index+n > m {
return false
}
for _, ch := range data[index+1 : index+n] {
if ch&mask2 != mask1 {
return false
}
}
index += n
}
return true
}
|