🌗 393. UTF-8 编码验证

吞佛童子2022年10月10日
  • algorithm
  • Array
  • 模拟
小于 1 分钟

🌗 393. UTF-8 编码验证

难度: 🌗

问题描述

img_32.png


解法

class Solution {
    int monitor = 128;
    int max = 191;
    public boolean validUtf8(int[] data) {
        // 思路:
        // 遍历数组中每个子节的字符,判断是 几字节的字符
        // 1000 0000 = 128
        // 10xx xxxx ∈ [128, 191]
        int len = data.length;
        int index = 0;
        while(index < len) {
            int cur = data[index];
            int count = getNum(cur); // 判断当前字符是 几字节 的首子节
            // System.out.println(count);
            if(count == 1 || count > 4) {
                return false; // 不存在,10xx xxxx 不能作为首字节,同时题意中表面一个字符长度为 1-4 字节
            } else if(count == 0) {
                index ++;
            } else {
                // count >= 2
                for(int i = index + 1; i < index + count; i ++) {
                    if(i >= len) {
                        return false;
                    }
                    if(!isValid(data[i])) {
                        return false;
                    }
                }
                index += count;
            }
        }
        return true;
    }

    private int getNum(int cur) {
        int res = 0;
        while((cur & monitor) != 0) {
            res ++;
            cur <<= 1;
        }
        return res;
    }
    private boolean isValid(int cur) {
        return cur >= monitor && cur <= max;
    }
}

输出

img_31.png

上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou