1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public boolean validWordAbbreviation(String word, String abbr) {
if (abbr.length() > word.length())
return false;
int ptr1 = 0, ptr2 = 0;
while (ptr1 < word.length() && ptr2 < abbr.length()) {
if (Character.isDigit(abbr.charAt(ptr2))) {
if (abbr.charAt(ptr2) == '0')
return false;
int currNum = 0;
while (ptr2 < abbr.length() && Character.isDigit(abbr.charAt(ptr2))) {
currNum = currNum * 10 + abbr.charAt(ptr2) - '0';
ptr2 += 1;
}
if (ptr1 + currNum > word.length()) {
return false;
} else {
ptr1 += currNum;
}
} else if (word.charAt(ptr1) != abbr.charAt(ptr2)) {
return false;
} else {
ptr1 += 1;
ptr2 += 1;
}
}
return ptr1 == word.length() && ptr2 == abbr.length();
}
}

两个string互相抵消. 到最后必须两个都是刚好抵消完. 不多也不少.

时间复杂度: O(n) n是abbr的长度.
空间复杂度: O(1)