Very Straight-forward Java Solution


  • 0

    The idea is iterate both word and abbr, keep each index i and j, if they match, both i and j should reach its end. So comes below solution, watch out for 1 corner case, number cannot lead with '0'.

     public boolean validWordAbbreviation(String word, String abbr) {
        int i = 0, j = 0;
        while(i<word.length() && j<abbr.length()) {
            if(isAlphabet(abbr.charAt(j))) {
                if(abbr.charAt(j) != word.charAt(i))
                    return false;
                i++;
                j++;
            } else {
                if(abbr.charAt(j)=='0') // 0 corner case check
                    return false;
                // extract the number from abbr
                int k = j+1;
                for(; k<abbr.length(); k++)
                    if(isAlphabet(abbr.charAt(k)))
                        break;
                int n = Integer.parseInt(abbr.substring(j,k));
                i += n;
                j = k;
            }
        }
        return i==word.length() && j==abbr.length() ? true : false;
    }
    
    public boolean isAlphabet(char c) {
        return c >= 'a' && c <= 'z';
    }

Log in to reply
 

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