Easy to Understand O(N) JAVA solution


  • 0
    A
    public boolean validUtf8(int[] data) {
        int i =0;
        while(i<data.length){
            if(data[i] >> 7 == 0 ) { i++;} // 1 byte
            else if(data[i] >> 5 == 6 ) { i++; if(checkData(data, i, 1)) i++; else return false;} // 2 byte
            else if(data[i] >> 4 == 14 ) { i++; if(checkData(data, i, 2)) i +=2; else return false;} // 3 byte
            else if(data[i] >> 3 == 30 ) { i++; if(checkData(data, i, 3)) i +=3; else return false;} // 4 byte
            else return false;
        }
        return true;
    }
    boolean checkData(int[] data, int index, int count) {
        if(index+count > data.length) return false;
        while(count-- > 0) 
            if(data[index++] >>6 != 2) 
                return false;
        return true;
    }

Log in to reply
 

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