EASY UNDERSTAND SOLUTION(JAVA)


  • 0
    M

    the UTF-8 can be more than 4 bytes long actually, but in this problem, the length of the UTF-8 can only be between 1 and 4 and should be checked.

    public class Solution {
        public boolean validUtf8(int[] data) {
            for(int i=0;i<data.length;i++){
                int len=getLen(data[i]);
                if(len==0)continue;
                if(len==1||len+i>data.length||len>4)return false;
                for(int j=1;j<len;j++){
                    if((data[i+j]&0xC0)!=0x80)return false; //check '10XX XXXX'
                }
                i+=len-1;
            }
            return true;
        }
        public int getLen(int val){
            int ret=0;
            int num=0x80;
            while((num&val)!=0){
                ret++;
                num=num>>>1;
            }
            return ret;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.