05 August 2008
可以通过用它们的长度替换任意数量的非相邻、非空子字符串来缩写字符串。长度不应有前导零。
例如,诸如“substitution”之类的字符串可以缩写为(但不限于):
“s10n”(“s 替代”)
“sub4u4”(“替代”)
“12”(“替代”)
“su3i1u2on” (“subst i t u ti on”) “substitution”(没有替换子串)
以下不是有效的缩写:
“s55n” (“s ubsti tutio n”,被替换的子串是相邻的) “s010n”(有前导零) “s0substitution”(替换空子字符串) 给定一个字符串单词和一个缩写词 abbr,返回字符串是否匹配给定的缩写词。
子字符串是字符串中连续的非空字符序列。
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
class Solution {
//Iterate over the characters of abbr and skip number of characters of word. Then compare ith chracter of word with jth character of abbr.
public boolean validWordAbbreviation(String word, String abbr) {
int number = 0;
int index1 = 0, index2 = 0;
while (index1 < word.length() && index2 < abbr.length()) {
if (Character.isDigit(abbr.charAt(index2))) {
number = number * 10 + abbr.charAt(index2) - '0';
if (number == 0) {
return false;
}
index2++;
} else {
index1 += number;
if ( index1 >= word.length() || word.charAt(index1) != abbr.charAt(index2)) {
return false;
}
number = 0;
index1++;
index2++;
}
}
index1 += number;
return index1 == word.length() && index2 == abbr.length();
}
}
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
class Solution {
public boolean validWordAbbreviation(String word, String abbr) {
int lenWord = word.length();
int lenAbbr = abbr.length();
if (lenAbbr > lenWord)
return false;
int index = 0;
int dig = 0;
for (int i = 0; i < lenAbbr; i++) {
if (abbr.charAt(i) - '0' >= 0 && abbr.charAt(i) - '0' <= 9) {
dig = dig * 10 + abbr.charAt(i) - '0';
if (dig == 0)
return false;
} else {
index = index + dig;
if (lenWord - 1 < index) {
return false;
}
dig = 0;
if (abbr.charAt(i) == word.charAt(index)) {
index++;
} else {
return false;
}
}
}
index = index + dig;
return lenWord == index;
}
}