mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 393. UTF-8 Validation.md
This commit is contained in:
parent
14efa6bf79
commit
bb7f9375da
42
solutions/393. UTF-8 Validation.md
Normal file
42
solutions/393. UTF-8 Validation.md
Normal file
@ -0,0 +1,42 @@
|
||||
# [393. UTF-8 Validation](https://leetcode.com/problems/utf-8-validation/)
|
||||
# 思路
|
||||
|
||||
此题让我们验证给定的编码是否是合法的 UTF-8 编码。
|
||||
|
||||
此题感觉没啥好说的,按照题目进行验证即可,详见代码。
|
||||
|
||||
**需要注意的是题目给的是【单个字符】的UTF-8规则,而实际却让我们判断的是【字符序列】** 估计这也是为什么那么多人给此题倒赞吧....实属坑题
|
||||
|
||||
# C++
|
||||
``` C++
|
||||
class Solution {
|
||||
private:
|
||||
int pre_1(int n){ // 计算有多少个前导1
|
||||
int mask = 128;
|
||||
int res = 0;
|
||||
while(mask & n){
|
||||
res++;
|
||||
mask >>= 1;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
public:
|
||||
bool validUtf8(vector<int>& data) {
|
||||
int i = 0;
|
||||
# define start_with_10(n) ((n & 0x000000c0) == 128)
|
||||
while(i < data.size()){
|
||||
int num_pre1 = pre_1(data[i]);
|
||||
if(!num_pre1) i++;
|
||||
else{
|
||||
if(num_pre1 == 1 || num_pre1 > 4) return false;
|
||||
for(int j = 1; j < num_pre1; j++){
|
||||
if(j + i == data.size() || !start_with_10(data[j+i]))
|
||||
return false;
|
||||
}
|
||||
i += num_pre1;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
```
|
||||
Loading…
Reference in New Issue
Block a user