Valid Word Abbreviation
Given a non-empty string s
and an abbreviation abbr
, return whether the string matches with the given abbreviation.
A string such as "word"
contains only the following valid abbreviations:
["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]
Notice that only the above abbreviations are valid abbreviations of the string "word"
. Any other string is not a valid abbreviation of "word"
.
Note:
Assume s
contains only lowercase letters and abbr
contains only lowercase letters and digits.
Example 1:
Given s = "internationalization", abbr = "i12iz4n": Return true.
Example 2:
Given s = "apple", abbr = "a2e": Return false.
注意:考虑word=’a‘, abbr=’01‘, test case return false。因此,所有leading zeros的temp都需要返回false。
1 class Solution { 2 public: 3 bool validWordAbbreviation(string word, string abbr) { 4 int wordIndex = 0, abbrIndex = 0; 5 while (wordIndex < word.size()) { 6 int abbrIndexEnd = abbrIndex; 7 while (abbrIndexEnd < abbr.size() && isdigit(abbr[abbrIndexEnd])) 8 abbrIndexEnd++; 9 10 // is a char and we need to check whether word[wordIndex] = abbr[abbrIndex] 11 if (abbrIndexEnd == abbrIndex) { 12 if (word[wordIndex] != abbr[abbrIndex]) return false; 13 wordIndex++; 14 abbrIndex++; 15 } else { 16 string temp = abbr.substr(abbrIndex, abbrIndexEnd - abbrIndex); 17 if (temp[0] == '0') return false; 18 int abbrLength = atoi(temp.c_str()); 19 wordIndex += abbrLength; 20 abbrIndex = abbrIndexEnd; 21 } 22 } 23 return wordIndex == word.size() && abbrIndex == abbr.size(); 24 } 25 };