题目描述:
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.
class Solution {
public:
bool validWordAbbreviation(string word, string abbr) {
int i=0, j=0;
int count=0;
while(i<word.size()&&j<abbr.size())
{
if(abbr[j]=='0') return false;
while(j<abbr.size()&&abbr[j]>='0'&&abbr[j]<='9')
{
count*=10;
count+=abbr[j]-'0';
j++;
}
if(count>0)
{
i+=count;
count=0;
}
if(i<word.size()&&j<abbr.size())
{
if(word[i]!=abbr[j]) return false;
else i++, j++;
}
}
return i==word.size()&&j==abbr.size();
}
};
本文深入探讨了一种用于判断字符串是否符合特定缩写形式的有效算法。通过实例演示了如何使用该算法来验证一个字符串是否能够正确地被其缩写表示,如国际化的internationalization缩写为i12iz4n的匹配过程。文章详细解释了算法的工作原理,包括处理数字缩写和字符比较的过程。
3824

被折叠的 条评论
为什么被折叠?



