Simple Recursive Solution


  • 0
    F
     public boolean validWordAbbreviation(String word, String abbr) {
            if (word.length() == 0 || abbr.length() == 0) {
                return word.length() == 0 && abbr.length() == 0;
            }
            
            if (word.charAt(0) == abbr.charAt(0)) {
                return validWordAbbreviation(word.substring(1), abbr.substring(1));
            } else if (Character.isDigit(abbr.charAt(0))) {
                //deal with special case like ('a' & '01')
                if (abbr.charAt(0) == '0') {
                    return false;
                }
                int num = 0;
                int idx = 0;
                while (idx < abbr.length() && Character.isDigit(abbr.charAt(idx))) {
                    num = num * 10 + abbr.charAt(idx++) - '0';
                }
                if (num > word.length() || idx > abbr.length()) {
                    return false;
                }
                return validWordAbbreviation(word.substring(num), abbr.substring(idx));
            } 
            return false;
        }
    

Log in to reply
 

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