Given anon-emptystringsand an abbreviationabbr, 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:Assumescontains only lowercase letters andabbrcontains only lowercase letters and digits.
Example 1:Givens= "internationalization",abbr= "i12iz4n":Return true.
Example 2:Givens= "apple",abbr= "a2e":Return false.
妈的这个题贼恶心, 看似简单, 想错一点都不行, 刚开始逆向思维搞死我了, 最后正向考虑问题, 总算过了。
public boolean validWordAbbreviation(String word, String abbr) {
if(word.length() < abbr.length()){
return false;
}
int index_word = 0;
int index_abbr = 0;
while(index_word < word.length() && index_abbr < abbr.length()){
if(word.charAt(index_word) == abbr.charAt(index_abbr)){
index_word++;
index_abbr++;
}else if(abbr.charAt(index_abbr) >= '1' && abbr.charAt(index_abbr) <= '9'){
int start = index_abbr;
while(index_abbr < abbr.length()
&& abbr.charAt(index_abbr) >= '0'
&& abbr.charAt(index_abbr) <= '9'){
index_abbr++;
}
index_word += Integer.valueOf(abbr.substring(start, index_abbr));
}else{
return false;
}
}
return index_word == word.length() && index_abbr == abbr.length();
}