题目链接https://leetcode-cn.com/problems/utf-8-validation/题目:
Given an integer array data representing the data, return whether it is a valid UTF-8 encoding.
A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:
For a 1-byte character, the first bit is a 0, followed by its Unicode code.
For an n-bytes character, the first n bits are all one's, the n + 1 bit is 0, followed by n - 1 bytes with the most significant 2 bits being 10.
This is how the UTF-8 encoding would work:
Char. number range | UTF-8 octet sequence
(hexadecimal) | (binary)
--------------------+---------------------------------------------
0000 0000-0000 007F | 0xxxxxxx
0000 0080-0000 07FF | 110xxxxx 10xxxxxx
0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
Note: The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data.
思路:
最开始的想法是把给定的整数转化为二进制数再进行判断。不过这一步很明显是多余的,其实直接整数利用位运算判断前几位的几个情况即可。注意边界条件的处理,在判断array[i+1]的时候需要先判断有没有数组越界!另外,循环变量的处理也需要注意:不能多也不能少加,continue之后会执行一次i++!
一开始想要转化为二进制却不知道从何下手,有空需要复习进制转化的有关知识。
题解:
class Solution {
public:
bool validUtf8(vector<int>& data) {
int index=0, len=data.size();
for(int i=0;i<len;i++){
if(data[i]>>3==(2+4+8+16)){
cout<<"find four bytes\n";
if(i==len-1 || data[i+1]>>6!=2) return false;
if(i==len-2 || data[i+2]>>6!=2) return false;
if(i==len-3 || data[i+3]>>6!=2) return false;
i+=3;
}
else if(data[i]>>4==(2+4+8)){
cout<<"find three bytes\n";
if(i==len-1 || data[i+1]>>6!=2) return false;
if(i==len-2 || data[i+2]>>6!=2) return false;
i+=2;
}
else if(data[i]>>5==(2+4)){
cout<<"find two bytes\n";
if(i==len-1 || data[i+1]>>6!=2) return false;
i+=1;
}
else if(data[i]>>7==0) {
cout<<"find one byte\n";
continue;
}
else return false;
}
return true;
}
};