本文主要是介绍Java | Leetcode Java题解之第393题UTF-8编码验证,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
题解:
class Solution {static final int MASK1 = 1 << 7;static final int MASK2 = (1 << 7) + (1 << 6);public boolean validUtf8(int[] data) {int m = data.length;int index = 0;while (index < m) {int num = data[index];int n = getBytes(num);if (n < 0 || index + n > m) {return false;}for (int i = 1; i < n; i++) {if (!isValid(data[index + i])) {return false;}}index += n;}return true;}public int getBytes(int num) {if ((num & MASK1) == 0) {return 1;}int n = 0;int mask = MASK1;while ((num & mask) != 0) {n++;if (n > 4) {return -1;}mask >>= 1;}return n >= 2 ? n : -1;}public boolean isValid(int num) {return (num & MASK2) == MASK1;}
}
这篇关于Java | Leetcode Java题解之第393题UTF-8编码验证的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!