本文主要是介绍leetcode 393. UTF-8 Validation | 393. UTF-8 编码验证(Java),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目
https://leetcode.com/problems/utf-8-validation/
题解
分析完情况之后,这题就是 if-else 堆起来的而已。
class Solution {public boolean validUtf8(int[] data) {for (int i = 0; i < data.length; i++) {int[] b = h2b(data[i]);int L = getLen(b);if (L == -1) return false;for (int j = 0; j < L - 1; j++) {if (i >= data.length - 1 || !check10(h2b(data[++i]))) return false;}}return true;}public boolean check10(int[] b) {return b[0] == 1 && b[1] == 0;}public int getLen(int[] b) {if (b[0] == 0) return 1;else if (b[0] == 1 && b[1] == 1 && b[2] == 0) return 2;else if (b[0] == 1 && b[1] == 1 && b[2] == 1 && b[3] == 0) return 3;else if (b[0] == 1 && b[1] == 1 && b[2] == 1 && b[3] == 1 && b[4] == 0) return 4;else return -1;}public int[] h2b(int i) { // hex to binint[] a = new int[8];int p = 0;while (i > 0) {a[8 - p - 1] = i % 2;p++;i /= 2;}return a;}
}
这篇关于leetcode 393. UTF-8 Validation | 393. UTF-8 编码验证(Java)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!