Wednesday, September 20, 2017

393. UTF-8 Validation


报错的算是一个edge case
如果只有1byte,应该是0 开头
也就是说不存在只有一个1开头的meta data

Input:[145]
Output:true
Expected:false
10010001

68.61 %

class Solution {
    public boolean validUtf8(int[] data) {
        if (data == null || data.length == 0) return false;
        return helper(data, 0, 0);
    }
    private boolean helper(int[] data, int index, int toMatch) {
        if (index == data.length) return toMatch == 0;
        int curr = data[index];
     
        if (toMatch != 0) {
            if (curr >> 6 != 0b10) return false;
            else return helper(data, index + 1, toMatch - 1);
        }
        // get the count of 1s
        int count = 0;
        int bit = 7;
        while ((curr & (1 << bit--)) != 0) {
            count++;
        }
        // can't be 1 since 1 byte is a special case
        // can't be more than 4 bytes
        if (count == 1 || count > 4) return false;
        count = count == 0 ? 0 : count - 1;
        return helper(data, index + 1, count);
    }
}

No comments:

Post a Comment