C++ solution by traversing the abbreviations


  • 0
    M
        bool validWordAbbreviation(string word, string abbr) {
        int abbr_len = abbr.length();
    
        int word_index = 0;
        int char_count = 0;
        for(int i = 0; i < abbr_len; ++i){
            if(abbr[i] >= 'a' && abbr[i] <= 'z'){
                if(abbr[i] != word[char_count + word_index]){
                    return false;
                }
                char_count++;
            }else{
                string str_dig;
                str_dig.push_back(abbr[i]);
                int count = 1;
                while(i + count < abbr_len && abbr[i + count] >= '0' && abbr[i + count] <= '9'){
                    str_dig += abbr[i + count];
                    count++;
                }
                if(str_dig[0] == '0'){
                    return false;
                }
                word_index += stoi(str_dig);
                i += count - 1;
            }
        }
        return word_index + char_count == word.length();
        }
    

Log in to reply
 

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