Simple straightforward Java solution by iterating on the shorter abbreviation


  • 0
    A
    class Solution {
    public boolean validWordAbbreviation(String word, String abbr) {
        // algorithm 2017/09/03: simply match by iterating the abbr string
        if (null == word || null == abbr) {
            return false;
        }
        int wordLen = word.length();
        int abbrLen = abbr.length();
        if (0 == wordLen && 0 == abbrLen) {
            return true;
        }
        if (0 == wordLen || 0 == abbrLen) {
            return false;
        }
        if (wordLen < abbrLen) {
            return false;
        }
        
        // normalized both strings by appending a SPACE
        word = word + " ";
        abbr = abbr + " ";
        wordLen ++;
        abbrLen ++;
        
        int wordIndex     = 0;
        Integer shortened = null;
        
        for (int abbrIndex = 0; abbrIndex < abbrLen; abbrIndex++) {
            char ch = abbr.charAt(abbrIndex);
            if (ch < '0' || ch > '9') {
                // find a char, but immediately before do we see a number?
                if (null != shortened) {
                    // skip wordIndex and remember to reset the shortened count
                    wordIndex += shortened; 
                    shortened = null;      // use Integer object could be better
                }
                if (wordIndex >= wordLen) {
                    return false;
                }
                if (ch != word.charAt(wordIndex)) {
                    return false;
                } else {
                    wordIndex++;        // both indices increase by 1
                }
            } else {
                // seeing an abbreviation
                if (null == shortened) {
                    shortened = (ch - '0');
                    // notice the shortened presentation cannot be started with 0, and cannot be 0
                    if (0 == shortened) {
                        return false;
                    }
                } else {
                    shortened = 10 * shortened + (ch - '0');
                }
            }
        }
        
        return true;
    }
    

    }


Log in to reply
 

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