C++ 6ms 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(); wi += skip ? skip : 1, ai += skip ? 0 : 1, skip = 0) {
                // extract number of skips
                while (ai < abbr.length() && isdigit(abbr[ai])) { 
                    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 && (ai == abbr.length() || word[wi] != abbr[ai])) { return false; }
            }
            
            // both word and abbr need to be completedly processed
            return wi == word.length() && ai == abbr.length();
    }
    

Log in to reply
 

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