Created
September 9, 2016 02:41
-
-
Save eclipselu/777b6564b156e04c0035e675c822760c to your computer and use it in GitHub Desktop.
Valid UTF8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool validUtf8(vector<int>& data) { | |
return isValid(data, 0); | |
} | |
private: | |
bool isValid(vector<int> &data, int startIndex) { | |
if (startIndex == data.size()) | |
return true; | |
int n = getBytes(data[startIndex]); | |
if (n < 0) | |
return false; | |
for (int i = 1; i < n; ++i) { | |
if (startIndex + i == data.size()) | |
return false; | |
if (data[startIndex + i] >> 6 != 0b10) | |
return false; | |
} | |
return isValid(data, startIndex + n); | |
} | |
int getBytes(int firstNum) { | |
if ((firstNum >> 7) == 0) | |
return 1; | |
else if ((firstNum >> 5) == 0b110) | |
return 2; | |
else if ((firstNum >> 4) == 0b1110) | |
return 3; | |
else if ((firstNum >> 3) == 0b11110) | |
return 4; | |
else | |
return -1; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment