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.
思路:
1. 判断是否match,简单的方法,就是two pointer,两个指针分别指向两个string,按照规则从左往右!
2. 难点是:从abbr中提取数字并组合得到对应的integer
3. 需注意的是,abbr只能是字母和数字,而且数字不能是0或0开头的数,但“10”是合法的。
bool validWordAbbreviation(string word, string abbr) {
int m=word.size(),n=abbr.size();
int i=0,j=0;
while(i<m&&j<n){
if(abbr[j]=='0')//遇到以0开头的数字或0,非法!
return false;
else if(abbr[j]>='1'&&abbr[j]<='9'){
int count=0;
while(j<n&&abbr[j]>='0'&&abbr[j]<='9'){//0允许出现在数字中间的位置
count=count*10+abbr[j]-'0';
j++;
}
i+=count;
}else
if(abbr[j++]!=word[i++]) return false;
}
return i==m&&j==n;//corner case:保证长度相等
}