Easy java solution


  • 0
    D
    public class Solution {
        public boolean validUtf8(int[] data) {
            
            //Base case: if array is empty , return false
            if(data.length==0 || data==null)
                return false;
                
            //General case : if values are present
            //stringbuilder to store the configuration
            StringBuilder sequence=new StringBuilder();
            
            //for loop to iterate through the string
            for(int i=0;i<data.length;i++)
            {
                int number=data[i];
                
                //add the configuration to the sequence
                sequence.append(convertNumberToSequence(number));
            }
            
            //to check if the sequence is valid
            int index=0;
            
            while(index<sequence.length())
            {
                int oneCounter=0;
                
                int start=index;
                
                //count number of ones
                while(start<sequence.length() && sequence.charAt(start++)=='1')
                    oneCounter++;
                
                //if more than 1 byte, check if its valid
                if(oneCounter--!=0)
                {
                    
                    
                    //if only one 1 is present, return false as it is not valid
                    if(oneCounter==0)
                        return false;
                   
                   //check to see if corresbonding bytes are valid
                   while(oneCounter-->0)
                   {
                       index+=8;
                       
                       start=index;
                       
                    //if out of bounds or first character is not a 1 and second character is not a 0, return false
                        if(start>=sequence.length() || sequence.charAt(start)!='1' || sequence.charAt(start+1)!='0')
                            return false;
                    //else continue
                       
                   }
                    
                }
                
                //go to the next byte
                index+=8;
            }
            
            return true;
            
            
            
        }
        
        public String convertNumberToSequence(int number)
        {
            StringBuilder answer=new StringBuilder();
            
            for(int i=7;i>=0;i--)
            {
                if(Math.pow(2,i)<=number)
                {
                    number=number-(int)Math.pow(2,i);
                    answer.append("1");
                }
                else
                    answer.append("0");
            }
            
            return answer.toString();
        }
    }
    

Log in to reply
 

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