408. Valid Word Abbreviation
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:
思路:
用两个指针遍历两个字符串。循环条件可以有多种处理方法,但是需要注意的是如果是||,要防止overflow,如果是&&,要在return前检查是否两个指针都已经遍历结束(任何一个结束了而另一个没有结束都属于invalid)。这里使用&&,也就是其中一个结束即终止。整体是,如果abbr里仍然是数字,p1 不动,p2向前累加直至不是数字,将这个数字告诉p1,num清零,跳至相应位置,进行比较,继续移动。有些坑需要注意:1. 任何时候以‘0’为开始的字符都是不合法的,但是‘10’,‘20‘合法。2. p1在循环内跳了,需要防范p1 overflow。3. 最后一轮num读取后,如何使用?这里是最后与p1相加再check一次。
易错点
上述所有。
Complexity
Time complexity: O(n)
Space complexity: O(1)
class Solution {
public:
bool validWordAbbreviation(string word, string abbr) {
int p1 = 0, p2 = 0, num = 0;
while (p1 < word.size() && p2 < abbr.size()) {
if (isdigit(abbr[p2])) {
if (abbr[p2] == '0' && num == 0) return false;
num = num * 10 + abbr[p2] - '0';
p2++;
}
else {
p1 += num;
num = 0;
if (p1 >= word.size() || word[p1] != abbr[p2]) return false;
p1++; p2++;
}
}
return num + p1 == word.size() && p2 == abbr.size();
}
};