Easy to understand Java solution


  • 0
    P
    class Solution {
        public boolean validWordAbbreviation(String word, String abbr) {
            int start=-1;
            int counter=0;
            if (abbr.length()>word.length())return false;
            for (int i=0;i<abbr.length();i++){
                start++;
                
                if (start>=word.length()){
                    return false;
                }            
                
                if (Character.isLetter(abbr.charAt(i))){
                    
                    if (abbr.charAt(i)!=word.charAt(start)){
                        return false;
                    }                
                }
                else {
                        int digit = abbr.charAt(i)-'0';
                    if (digit==0){
                        return false;
                    }
                        counter=i+1;
                        while (counter<abbr.length()&&Character.isDigit(abbr.charAt(counter))){
                            digit = (digit*10)+(abbr.charAt(counter)-'0');    
                            counter++;
                        }
                        start=start+digit-1;                 
                         i=counter-1;                    
                    }                                   
                }          
            
            if (start!=word.length()-1){
                    return false;
                }
            
            return true;
        }
    }
    

Log in to reply
 

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