Share my Java solution


  • 0
    O
    public boolean validUtf8(int[] data) {
            int len = data.length;
            if(len == 0) return false;
            int i = 0;
            int count = 0;
            while(i < len){
                while(count > 0){ // for n-bytes character
                    if(i >= len) return false;
                    int check = data[i] >> 6; // check if the most two significant bits is 10
                    if(check != 2) return false;
                    count--;
                    i++;
                }
                if(i < len && (data[i]&128) == 128){ // check if the most significant bit is 1
                    data[i] = data[i] << 1;
                    while((data[i]&128) == 128){
                        count++;
                        data[i] = data[i] << 1;
                    }
                    if(count > 3 || count == 0) return false;
                }
                i++;
            }
            if(count != 0) return false;
            return true;
        }
    

Log in to reply
 

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