Given an integer array data representing the data, return whether it is a valid UTF-8 encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters).
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:
Number of Bytes | UTF-8 Octet Sequence
| (binary)
--------------------+-----------------------------------------
1 | 0xxxxxxx
2 | 110xxxxx 10xxxxxx
3 | 1110xxxx 10xxxxxx 10xxxxxx
4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
x denotes a bit in the binary form of a byte that may be either 0 or 1.
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.
Example 1:
Input: data = [197,130,1]
Output: true
Explanation: data represents the octet sequence: 11000101 10000010 00000001.
It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.
Example 2:
Input: data = [235,140,4]
Output: false
Explanation: data represented the octet sequence: 11101011 10001100 00000100.
The first 3 bits are all one’s and the 4th bit is 0 means it is a 3-bytes character.
The next byte is a continuation byte which starts with 10 and that’s correct.
But the second continuation byte does not start with 10, so it is invalid.
看着很绕,简单解释下,
UFT-8是1~4byte长的,不能超过4byte.
4个byte可能出现的4种情况都在表里,不符合的就是false。
那你会说1 <= data.length <= 20000,data的长度可能到20000啊,怎么可能只有4 byte。
1~4 byte代表一个字符,后面的就是另一个字符,1~4 byte为一组。
思路:
经过上面的解释,可以做出如下分析。
第一个byte开头为0的不用考虑,肯定是UTF-8,跳过。
然后就是表里的case 2,3,4.
利用bit移位来判断,cnt记录后面应该出现多少个开头为10的byte.

该博客探讨了如何验证一个整数数组是否代表有效的UTF-8编码。UTF-8编码规则包括1至4字节字符的定义,博客通过示例解释了编码的工作原理,并提供了两种不同的Java代码实现来检查输入数据的合法性。代码通过位移操作或与运算来判断每个字节是否符合UTF-8编码标准。
最低0.47元/天 解锁文章
973

被折叠的 条评论
为什么被折叠?



