Implement rules one by one. Keep calm, be patient..
public class Solution {
public boolean validUtf8(int[] data) {
if(data == null || data.length == 0){
return true;
}
for(int i=0; i<data.length; i++){
if(((1<<7)&data[i]) == 0){ // 1 byte character -> skip
continue;
} else{
// get number of bytes (from left to right)
int count = 0;
while(count<=7 && ((1<<(7-count))&data[i])>0){
count++;
}
if(count >7 || count == 1){
return false;
}
// check if next bit = '0'
if(((1<<(7-count)) & data[i]) >0){
return false;
}
// check if following bytes are start with '10'
for(int j=i+1; j<i+count; j++){
if(j>= data.length){
return false;
}
if(!isValidSub(data[j])){
return false;
}
}
i += count - 1;
}
}
return true;
}
public boolean isValidSub(int num){ // check if start with '10'
if((((1<<7)&num) >0) && (((1<<6)&num)==0)){
return true;
}
return false;
}
}