本文主要是介绍C++ | Leetcode C++题解之第393题UTF-8编码验证,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
题解:
class Solution {
public:static const int MASK1 = 1 << 7;static const int MASK2 = (1 << 7) + (1 << 6);bool isValid(int num) {return (num & MASK2) == MASK1;}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;}bool validUtf8(vector<int>& data) {int m = data.size();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;}
};
这篇关于C++ | Leetcode C++题解之第393题UTF-8编码验证的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!