-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path13-utf-8-validation.rs
34 lines (33 loc) · 1.05 KB
/
13-utf-8-validation.rs
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
// https://leetcode-cn.com/problems/utf-8-validation/
impl Solution {
pub fn valid_utf8(data: Vec<i32>) -> bool {
let mut i = 0;
while i < data.len() {
if Solution::get_bit(data[i], 8) == 1 {
let mut j = 7;
let cur = data[i];
if Solution::get_bit(cur,7) == 0 {
return false;
}
while j >= 5 && Solution::get_bit(cur, j) == 1 {
i += 1;
j -= 1;
if i >= data.len() {
return false;
}
if Solution::get_bit(data[i], 8) != 1 || Solution::get_bit(data[i], 7) != 0 {
return false;
}
}
if j == 4 && Solution::get_bit(cur,j) == 1 {
return false;
}
}
i += 1;
}
true
}
fn get_bit(x: i32, n: usize) -> i32 {
(x >> (n - 1)) & 1
}
}