Given an integer array data representing the data, return whether it is a valid UTF-8 encoding.
A character in UTF-8 can be 1 to 4 bytes long and follows these rules:
-
For a 1-byte character, the first bit is
0
, followed by its Unicode code.
-
For an n-byte character, the first n bits are all ones, bit n + 1 is
0
, and it is followed by n - 1 bytes whose two most significant bits are
10
.
This is how the UTF-8 encoding works:
| Number of bytes | UTF-8 octet sequence (binary) |
|---|
| 1 | 0xxxxxxx |
| 2 | 110xxxxx 10xxxxxx |
| 3 | 1110xxxx 10xxxxxx 10xxxxxx |
| 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
The input is an array of integers. Only the least significant 8 bits of each integer store data, so each integer represents one byte.
Function Signature
def valid_utf8(data: list[int]) -> bool:
...
Rules
-
Check only the bit patterns in the table. A sequence whose bit patterns are right counts as valid even if it would decode to an overlong form, a surrogate, or a value above U+10FFFF.
-
The whole array must split into complete characters. A multi-byte character cut off by the end of
data
makes the encoding invalid.
Constraints
-
1 <= len(data) <= 2 * 10^4
-
0 <= data[i] <= 255
Examples
Input: data = [197, 130, 1]
Output: True
197 is 11000101, the lead byte of a 2-byte character, and 130 is 10000010, a valid continuation byte. 1 is 00000001, a complete 1-byte character, so the array holds two valid characters.
Input: data = [235, 140, 4]
Output: False
235 is 11101011, the lead byte of a 3-byte character. 140 is 10001100, a valid continuation byte, but 4 is 00000100, which does not start with 10.
Input: data = [230, 136]
Output: False
230 is 11100110, the lead byte of a 3-byte character, so two continuation bytes must follow. Only one (136, which is 10001000) is present before the array ends.