Simple two pointer solution


  • 0
        public boolean validWordAbbreviation(String word, String abbr) {
            int lhs = 0;
            int rhs = 0;
            
            while (lhs < word.length() && rhs < abbr.length()) {
                if (Character.isDigit(abbr.charAt(rhs))) {
                    if (abbr.charAt(rhs) == '0') break;
                    int advance = 0;
                    while (rhs < abbr.length() && Character.isDigit(abbr.charAt(rhs))) {
                        advance = advance * 10 + (abbr.charAt(rhs++) - '0');
                    }
                    
                    lhs += advance;
                } else {
                    if (word.charAt(lhs) == abbr.charAt(rhs)) {
                        lhs++; rhs++;
                    } else {
                        break;
                    }
                }
            }
            
            return lhs == word.length() && rhs == abbr.length();
        }
    

Log in to reply
 

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