Clean 1 pass Java solution 7ms with comments


  • 0
    M
        public boolean validUtf8(int[] data) {
            if(data == null || data.length == 0)
                return false;
            int i = 0;
            
            while(i < data.length){
                //check how many bytes that character is
                //4-byte char, 30: 11110
                if(data[i] >> 3 == 30){
                    if(i + 3 >= data.length || !(isValid(data[++i]) && isValid(data[++i]) && isValid(data[++i])))
                        return false;
                }
                //3-byte char, 14: 1110
                else if(data[i] >> 4 == 14){
                    if(i + 2 >= data.length || !(isValid(data[++i]) && isValid(data[++i])))
                        return false;
                }
                //2-byte char, 6: 110
                else if(data[i] >> 5 == 6){
                    if(i + 1 >= data.length || !isValid(data[++i]))
                        return false;
                }
                //1-byte char
                else if(data[i] >> 7 == 0){
                    
                }
                //invalid
                else{
                    return false;
                }
                i++;
            }
            
            return true;
        }
        
        //to check if n is in format "10xxxxxx"
        private boolean isValid(int n){
            return (n >> 6) == 2;
        }
    

Log in to reply
 

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