其他分享
首页 > 其他分享> > 408. Valid Word Abbreviation

408. Valid Word Abbreviation

作者:互联网

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.
 1 class Solution {
 2     public boolean validWordAbbreviation(String word, String abbr) {
 3         int i = 0, j = 0;
 4         while (i < word.length() && j < abbr.length()) {
 5             if (word.charAt(i) == abbr.charAt(j)) {
 6                 ++i;++j;
 7                 continue;
 8             }
 9             if (abbr.charAt(j) <= '0' || abbr.charAt(j) > '9') {
10                 return false;
11             }
12             int start = j;
13             while (j < abbr.length() && abbr.charAt(j) >= '0' && abbr.charAt(j) <= '9') {
14                 ++j;
15             }
16             int num = Integer.valueOf(abbr.substring(start, j));
17             i += num;
18         }
19         return i == word.length() && j == abbr.length();
20     }
21 }

 

标签:Given,word,string,Abbreviation,only,Valid,abbr,Word,charAt
来源: https://www.cnblogs.com/beiyeqingteng/p/14523728.html