C++ 3ms 8 lines with comments


  • 0
    bool validWordAbbreviation(string word, string abbr) {
            int wi = 0, ai = 0;                                     // wi: position in word; ai: position in abbr
            
            // skip: number of skips in word indicated in abbr;
            for (int skip = 0; wi < word.length() && ai < abbr.length(); wi += skip ? skip : 1, ai += skip ? 0 : 1, skip = 0) {
                while (ai < abbr.length() && isdigit(abbr[ai])) {                       // extract number of skips
                    if ((skip = skip * 10 + (abbr[ai++] - '0')) == 0) { return false; } // can't accept leading '0'
                }
                
                // abbr is not valid if word[wi] and abbr[ai] don't match
                if (skip == 0 && word[wi] != abbr[ai]) { return false; }
            }
            
    
            return wi == word.length() && ai == abbr.length();  // both word and abbr need to be completed processed
    }
    

Log in to reply
 

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