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();
}