share my c++ solution


  • 0
    bool validWordAbbreviation(string word, string abbr) {
    	int wordIndex = 0;
    	int abbrIndex = 0;
    	for (; abbrIndex < abbr.size() && wordIndex < word.size(); abbrIndex++, wordIndex++) {
    		char c = abbr[abbrIndex];
    		if (isalpha(c) && word[wordIndex] != c)
    			return false;
    		else if (isdigit(c)) {
    			// if we allow 0 to be the first digit of a number, then we would have infinite number of valid abbreviations
    			if (c == '0')
    				return false;
    			int num = c - '0';
    			while (abbrIndex < abbr.size() && isdigit(abbr[abbrIndex+1]))
    				num = num*10 + (abbr[++abbrIndex] - '0');
    			wordIndex += num-1;
    		}
    	}
    	return wordIndex == word.size() && abbrIndex == abbr.size();
    }
    

Log in to reply
 

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