给一个 非空 字符串 s 和一个单词缩写 abbr ,判断这个缩写是否可以是给定单词的缩写。
字符串 “word” 的所有有效缩写为:
["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d",
"wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]
注意单词 "word" 的所有有效缩写仅包含以上这些。
任何其他的字符串都不是 "word" 的有效缩写。
注意:
假设字符串 s 仅包含小写字母且 abbr 只包含小写字母和数字。
示例 1:
给定 s = "internationalization", abbr = "i12iz4n":
函数返回 true.
示例 2:
给定 s = "apple", abbr = "a2e":
函数返回 false.
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/valid-word-abbreviation 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"a"
"01"
预期:
false
"internationalization"
"i5a11o1"
预期:
true
class Solution {
public:
bool validWordAbbreviation(string word, string abbr) {
int i = 0, n = 0, j = 0;
while(i<word.size() && j < abbr.size())
{
n = 0;
if(isdigit(abbr[j]))
{
if(abbr[j]=='0')//"a","01"
return false;
while(j < abbr.size() && isdigit(abbr[j]))
n = n*10+abbr[j++]-'0';
}
i += n;
if(i<word.size() && j<abbr.size() && word[i] != abbr[j])
return false;
else if((i<word.size()&&j>=abbr.size())||(i>=word.size()&&j<abbr.size()))
return false;
else if(i==word.size() && j==abbr.size())
return true;//这里加一条,可能以数字结尾,下面++,出了循环,最后条件不成立
i++,j++;
}
return i==word.size() && j==abbr.size();
}
};
4 ms 6 MB
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有