3ms C++ solution


  • 0
    S
    class Solution {
    public:
        bool validWordAbbreviation(string word, string abbr) {
            int word_i = 0;
            int abbr_i = 0;
            int abbr_size = abbr.size();
            int word_size = word.size();
            while (abbr_i < abbr_size && word_i < word_size){
                if(isDigit(abbr[abbr_i])){
                    if (abbr[abbr_i] == '0') return false;
                    string tempNum = "";
                    while (isDigit(abbr[abbr_i])){
                        tempNum += abbr[abbr_i];
                        ++abbr_i;
                        if (abbr_i > abbr_size - 1) break;
                    }
                    word_i += digitToInt(tempNum);
                } else {
                    if(abbr[abbr_i] != word[word_i]) return false;
                    ++word_i;
                    ++abbr_i;
                }
            }
            
            return (abbr_i == abbr_size && word_i == word_size);
        }
        
        bool isDigit(char c){
            return (c >= '0' && c <= '9');
        }
        int digitToInt (string s){
            return stoi(s);
        }
    };
    

Log in to reply
 

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