Problem 679
UTF-8 Validation
Medium · 20 pts · Array, Bit Manipulation
Problem
Decide whether a sequence of bytes is valid UTF-8. A character is 1 to 4 bytes long. A 1-byte character starts with bit 0. An n-byte character (n = 2, 3 or 4) starts with n ones followed by a 0, and is followed by n - 1 continuation bytes that each start with 10. Each input integer is one byte (only its lowest 8 bits matter, and all are in 0..255). Walk through the bytes, read the length from each leading byte, and check its continuation bytes.
Input
The first line contains an integer N, the size of the array. The second line contains N space-separated integers A[0], A[1], ..., A[N-1]. Each value is between 0 and 255.
Output
Print YES if the data is valid UTF-8, otherwise NO.
Constraints
1 <= N <= 20000; 0 <= A[i] <= 255
Example input
3 197 130 1
Example output
YES
Explanation
The bytes 197 130 1 are 11000101 10000010 00000001. The first two form a valid 2-byte character (110... followed by 10...), and 00000001 is a 1-byte character. So the answer is YES.