November 27, 2019

408. Valid Word Abbreviation

408. Valid Word Abbreviation

Use two pointers (one for word, the other for abbreviation) to traverse the two strings at the same time.

class Solution {
    public boolean validWordAbbreviation(String word, String abbr) {
        if (word == null && abbr == null) return true;
        if (word == null || abbr == null) return false;
        
        int i = 0;
        int j = 0;
        while (i < word.length() && j < abbr.length()) {
            if (word.charAt(i) == abbr.charAt(j)) {
                i++;
                j++;
            } else if (abbr.charAt(j) > '0' && abbr.charAt(j) <= '9') { // Corner case: If the number starts with '0', it's invalid.
                int start = j;
                while (j < abbr.length() && abbr.charAt(j) >= '0' && abbr.charAt(j) <= '9') {
                    j++;
                }
                int num = Integer.valueOf(abbr.substring(start, j));
                i += num;
            } else {
                return false;
            }
        }
        return (i == word.length()) && (j == abbr.length());
    }
}
comments powered by Disqus