[LintCode] Check Word Abbreviation

Given a non-empty string word 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

Notice that only the above abbreviations are valid abbreviations of the string word. Any other string is not a valid abbreviation of word.

 

Example

Example 1:

Given s = "internationalization", abbr = "i12iz4n":
Return true.

Example 2:

Given s = "apple", abbr = "a2e":
Return false.


Solution.
This problem is fairly simple and straightforward. The only tricky part is all the corner cases.


1. if there is a number in the abbr string, parse it to num.
2. advance the index of word by num.
3. if both i and j are still in bound, check if match or not.
4. repeat the above steps until either i or j is out of bound.
5. check if both i and j are out of bound.

 1 public class Solution {
 2     public boolean validWordAbbreviation(String word, String abbr) {
 3         if(abbr == null || abbr.length() == 0){
 4             return false;
 5         }
 6         int i = 0;
 7         int j = 0;
 8         int num = 0;
 9         while(i < word.length() && j < abbr.length()){
10             while(j < abbr.length() && abbr.charAt(j) >= '0' 
11                     && abbr.charAt(j) <= '9'){
12                 num = num * 10 + (abbr.charAt(j) - '0');   
13                 if(num == 0){
14                     return false;
15                 }
16                 j++;
17             }
18             i += num;
19             num = 0;
20             if(i >= word.length() || j >= abbr.length()){
21                 break;
22             }
23             else if(word.charAt(i) != abbr.charAt(j)){
24                 return false;    
25             }
26             else{
27                 i++;
28                 j++;
29             }
30         }
31         return i == word.length() && j == abbr.length();
32     }
33 }

 

 

Related Problems

Word Abbreviation

 

posted @ 2017-06-06 03:43  Review->Improve  阅读(643)  评论(0编辑  收藏  举报