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:

1
["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:

1
2
3
Given s = "internationalization", abbr = "i12iz4n":
Return true.

Example 2:

1
2
3
Given s = "apple", abbr = "a2e":
Return false.

解法1:

string类的题目似乎用指针可以规避掉一些cornercase的处理。这题用两个指针维护当前比较的起始位置。
先比较是否相等,如果相等则都往前进一步。
如果不相等,则考虑abbr是否为数字,把数字parse出来后i相应的比较位置就前进对应的数字个数。
这里要注意的是,数字的开端不能为0.
C++

1

Java

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
30
31
32
public class Solution {
public boolean validWordAbbreviation(String word, String abbr) {
if (word == null && abbr == null) {
return true;
} else if (word == null || abbr == null) {
return false;
}
int i = 0, j = 0;
while (i < word.length() && j < abbr.length()) {
char w = word.charAt(i);
char a = abbr.charAt(j);
if (w == a) {
i++;
j++;
} else if (a > '0' && a <= '9') {
int start = j;
while (j < abbr.length() && abbr.charAt(j) >= '0' && abbr.charAt(j) <= '9') {
j++;
}
i += Integer.valueOf(abbr.substring(start, j));
} else {
return false;
}
}
return i == word.length() && j == abbr.length();
}
}