My straight-forward c++ one pass solution


  • 0
        bool isDigit(char c) {
            return c >= '0' && c <= '9';
        }
    
        bool validWordAbbreviation(string word, string abbr) {
            if (word == "")
                return abbr == "";
                
            int i = 0; // pointer for word
            int j = 0; // pointer for abbr
            
            while (i < word.size() && j < abbr.size()) {
                if (!isDigit(abbr[j])) { // is letter, must match current char
                    if (abbr[j] != word[i])
                        return false;
                    i ++;
                    j ++;
                } else { // is digit
                    if (abbr[j] == '0') // if number starts with 0, invalid abbr
                        return false;
                        
                    int len = 0;
                    while (j < abbr.size() && isDigit(abbr[j]))
                        len = 10 * len + abbr[j++] - '0';
                    i += len;
                }
            }
            
            return i == word.size() && j == abbr.size();
        }
    

Log in to reply
 

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