Java non-regex, easy understand and short solution


  • 0
    X
    public boolean validWordAbbreviation(String word, String abbr) {
            int p1 = 0;
            int p2 = 0;
            
            while(p1 < word.length() && p2 < abbr.length()) {
                int num = 0;
                while( p2 < abbr.length() && Character.isDigit(abbr.charAt(p2))) { // Convert the digit part
                    int digit = abbr.charAt(p2) - '0';
                    // If the digit part starts with 0 then the abbreviation is invalid
                    if(num == 0 && digit == 0) return false;
                    num = num * 10 + digit;
                    p2 ++;
                }
                p1 += num;
                
                if(p1 >= word.length() || p2 >= abbr.length()) { 
                    if(p1 == word.length() && p2 == abbr.length()) return true;
                    return false;
                }
                
                if(word.charAt(p1) != abbr.charAt(p2)) return false;
                
                p1 ++;
                p2 ++;
            }
            
            return p1 == word.length() && p2 == abbr.length();
        }
    

Log in to reply
 

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