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
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. 如果是数字,吃数字
2. 如果count == 0, 说明大家都指向字符。那就对比字符
3. 如果不是数字,j += count。 此时i, j都会指向字符或超出范围,两者对比会交给下一次的循环。
注意几个corner case:
1. 数字开头为0: a0b
2. 末尾是数字: ab1。 最后检测长度的时候加上count
class Solution {
public boolean validWordAbbreviation(String word, String abbr) {
int i = 0, j = 0;
int count = 0;
while (i < abbr.length() && j < word.length()) {
char c = abbr.charAt(i);
if (Character.isDigit(c)) {
if (count == 0 && c <= '0') return false;
count = Character.getNumericValue(c) + count * 10;
i++;
}else if (count == 0) {
if (c != word.charAt(j)) return false;
i++;
j++;
}else {
j += count;
count = 0;
}
}
return i == abbr.length() && j + count == word.length();
}
}
No comments:
Post a Comment