0%

408. Valid Word Abbreviation

O(n) time O(1) space

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
bool validWordAbbreviation(string word, string abbr) {
word += " ", abbr += " "; // padding方便处理
int m = word.length(), n = abbr.length(), i = 0, j = 0;
for (int s = 0; i < m && j < n; i += s, ++j) {
if (isdigit(abbr[j])) {
if (abbr[j] == '0') return false; // 以0开头的数是非法的
int x = 0; // 一次性把整个数取出来
while (isdigit(abbr[j])) {
x = x * 10 + abbr[j] - '0';
++j;
}
--j; // 注意下标要回退一个
s = x;
} else {
if (word[i] != abbr[j]) return false;
s = 1;
}
}
return i == m && j == n; // 最后判断是否两个指针同时达到结尾
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
bool validWordAbbreviation(string word, string abbr) {
word += " ", abbr += " ";
int m = word.length(), n = abbr.length(), s = 0, i = 0, j = 0;
for (; i < m && j < n; ++j) {
if (isdigit(abbr[j])) {
if (s == 0 && abbr[j] == '0') return false;
s = s * 10 + abbr[j] - '0';
} else {
i += s;
s = 0;
if (i < m && word[i] != abbr[j]) return false;
++i;
}
}
return i == m && j == n;
}
};