给定一个非空字符串 word
和缩写 abbr
,返回字符串是否可以和给定的缩写匹配。
比如一个 “word”
的字符串仅包含以下有效缩写:
["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]
样例
样例 1:
给出 s = "internationalization", abbr = "i12iz4n":
返回 true。
样例 2:
给出 s = "apple", abbr = "a2e":
返回 false。
解题思路:
每次先判断两个字符串当前位置是否相等,如果相等都+1,否则缩写字符串肯定应该是数字,然后找出这个数字多少就把word的位置右移多少.在找出扎个数字的时候还要先判断是否有先导0,如果有的话就不符合.最后把word位置右移之后还要判断移动之后的位置字符是否相等,也就是说如果移动之后的位置如果不相等肯定也为false.
注意各种边界条件。此代码是网上的AC。
class Solution {
public:
/**
* @param word: a non-empty string
* @param abbr: an abbreviation
* @return: true if string matches with the given abbr or false
*/
bool validWordAbbreviation(string &word, string &abbr)
{
// write your code here
int k = 0, i = 0;
while(i < abbr.size())
{
if(word[k]==abbr[i])
{
i++;
k++;
continue;
}
int cnt = 0;
if(abbr[i] == '0')
return false;
while(isdigit(abbr[i]))
{
cnt = cnt*10 + (abbr[i]-'0');
i++;
}
k += cnt;
if(k > word.size() || word[k] != abbr[i]) return false;
}
return k==word.size();
}
};