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 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.
Show Similar Problems
这道题思路比较简单,但是后来处理边界条件上花了时间比较久。
思路是使用两个指针,分别从word, abbr的头开始走起,index2碰到数字的话,首先判断开头是否为0(这一点我挺费解的,为啥不能为0,后来测试用例告诉我这样不可以)。然后让index1 走相应的距离,然后再判断对应index1 index2的位置的值是否一样。不一样的话return false.
代码:
public boolean validWordAbbreviation(String word, String abbr) {
if(word == null || word.length() == 0 || abbr == null || abbr.length() == 0) return false;
int index1 = 0;
int index2 = 0;
int offset = 0;
while(index1<word.length() && index2 < abbr.length()){
char char2 = abbr.charAt(index2);
if(char2>='0' && char2 <='9'){
if(char2 == '0') return false;
while(char2>='0' && char2 <='9'){
offset = offset * 10 + char2 - '0';
index2++;
if(index2 == abbr.length()) break;
char2 = abbr.charAt(index2);
}
}
//System.out.println("offset"+ offset);
index1 += offset;
offset = 0;
if(index1 >= word.length()) break;
char char1 = word.charAt(index1);
if(char1 != char2){
return false;
}
index1++;
index2++;
}
return index1 == word.length() && index2 == abbr.length();
}