Skip to content

Instantly share code, notes, and snippets.

@eclipselu
Created September 9, 2016 02:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eclipselu/777b6564b156e04c0035e675c822760c to your computer and use it in GitHub Desktop.
Save eclipselu/777b6564b156e04c0035e675c822760c to your computer and use it in GitHub Desktop.
Valid UTF8
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