给定一个非空字符串 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
注意事项
注意只有以上缩写是字符串 word 合法的缩写。任何其他关于 word 的缩写都是不合法的。
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 sum=0;
int j=0;
for(int i=0;i<abbr.length();i++){
if(abbr[i]-'0'>=0&&abbr[i]-'0'<=9) {
sum=sum*10+(abbr[i]-'0');
if(sum==0) return false;
}else{
j=j+sum;
sum=0;
if(abbr[i]!=word[j]) return false;
j++;
}
}
if(sum)
if(j+sum==word.length()) return true;
else return false;
return true;
}
}; ```