Simple and short Java code - beats 98%


  • 0
    L
    public boolean validWordAbbreviation(String word, String abbr) {
            int i = 0;
            int j = 0;
            while( j < abbr.length() && i < word.length()){
            
                if(abbr.charAt(j) > '0' && abbr.charAt(j) < '9'){
                    int num = abbr.charAt(j++) - '0';
                    while(j < abbr.length() && abbr.charAt(j) >= '0' && abbr.charAt(j) <= '9' ){
                        num = num * 10 + (abbr.charAt(j++) - '0');
                    }
                    i = i + num;     
                }
                else{
                    if(abbr.charAt(j++) != word.charAt(i++)){             
                        return false;
                    }
                }
            }
            return i == word.length() && j == abbr.length();
        }
    

Log in to reply
 

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