Problem
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
nbits are all one’s, then + 1bit is0, followed byn - 1bytes with the most significant2bits being10.
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.
Examples
Example 1:
| |
Example 2:
| |
Solution
Method 1 - Bit Manipulation Using & Operation and Masking
Consider the following numbers, which represent the first byte in the four combinations (replacing all x with 0s):
- 0xxxxxxx = 0
- 110xxxxx = 192
- 1110xxxx = 224
- 11110xxx = 240
Next, let’s create masks for the & operator. We add an extra 1, so the result matches the numbers above. The masks (replacing x with 0s) are:
- 0xxxxxxx → 1xxxxxxx = 128
- 110xxxxx → 111xxxxx = 224
- 1110xxxx → 1111xxxx = 240
- 11110xxx → 11111xxx = 248
To determine the category of the current byte, we can use these masks to check if the byte fits the pattern. For example, for a 1-byte case, if 128 & byte == 0, the byte is valid. If 1111xxxx & byte == 1110xxxx, it indicates a 3-byte case, and we must ensure the next two bytes follow the correct pattern.
Algo
- Iterate through the array of bytes. For each byte, determine which case it falls into, i.e., whether it is the first byte of a 1-byte, 2-byte, 3-byte, or 4-byte sequence.
- Verify if the subsequent
numBytesmatch the pattern. The mask for all following bytes is1100000as the number pattern is10000000. If any mismatch occurs, return false. - Return true if all bytes follow the pattern.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n) - 🧺 Space complexity:
O(1)