0393.cpp (666B)
1 class Solution { 2 public: 3 bool validUtf8(const vector<int> &data) const { 4 static const uint8_t mask[] = {0x80, 0xE0, 0xF0, 0xF8}; 5 static const uint8_t val[] = {0x00, 0xC0, 0xE0, 0xF0}; 6 const int n = size(data); 7 8 for (int i = 0, j, k; i < n; i++) { 9 for (j = 0; j < 4; j++) { 10 if ((data[i] & mask[j]) != val[j]) continue; 11 break; 12 } 13 if (j == 4) return false; 14 15 for (k = 0; k < j && i + 1 < n; k++) { 16 if ((data[++i] & 0xC0) != 0x80) return false; 17 } 18 if (k != j) return false; 19 } 20 21 return true; 22 } 23 };