Simplest Java solution so far


  • 0
    R

    '''
    public static boolean validWordAbbreviation(String word, String abbr) {

        int wi = 0, ai = 0;
        int cnt = 0;
        while (ai < abbr.length()) {
            while (ai < abbr.length() && Character.isDigit(abbr.charAt(ai)) ) {
                // make sure abbreviated cnt doesn't start with 0
                if (abbr.charAt(ai) == '0' && cnt==0) return false;
                cnt = cnt * 10 + abbr.charAt(ai++) - '0';
            }
            wi += cnt;
            if (ai < abbr.length()) {
                cnt = 0;
                if (wi >= word.length()  // if wi == word.length(), ai == abbr.length(), whereas here ai < abbr.length()
                        || abbr.charAt(ai++) != word.charAt(wi++)) return false;
            }
        }
        return wi == word.length();
    }
    

    '''


Log in to reply
 

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