408. Valid Word Abbreviation

来看一题水平吊打的题

自己的方法,就是一个一个match咯&

当word和abbr都没有走到尽头:

  如果当前位上的字母相等,那么i++, j++, continue;

  如果abbr当前位置上的不是数字(因为之前如果是字母已经完成了匹配了),就返回false

  如果找到abbr上的数字,i+=num

退出时候看是不是i,j都正好走到了头

需要注意的就是可能会出现Invalid的数字,比如01这样,就是一个数字必须是[1-9]\\d*。

 1     public boolean validWordAbbreviation(String word, String abbr) {
 2         if(word == null || abbr == null) {
 3             return false;
 4         }
 5         int i = 0;
 6         int j = 0;
 7         while(i < word.length() && j < abbr.length()) {
 8             if(word.charAt(i) == abbr.charAt(j)) {
 9                 i++;
10                 j++;
11                 continue;
12             }
13             if(abbr.charAt(j) < '0' || abbr.charAt(j) > '9') {
14                 return false;
15             }
16             int start = j;
17             while(j < abbr.length() && abbr.charAt(j) >= '0' && abbr.charAt(j) <= '9') {
18                 j++;
19             }
20             String numStr = abbr.substring(start, j);
21             if(numStr.charAt(0) == '0') {
22                 return false;
23             }
24             int num = Integer.parseInt(numStr);
25             i += num;
26         }
27         return i == word.length() && j == abbr.length();
28     }

 

 

然后以下是Stefan Pochmann大神做的……吊打哈哈

即把"i12iz4n"这样的缩写转换成"i.{12}iz.{4}n"

1     public boolean validWordAbbreviation(String word, String abbr) {
2         return word.matches(abbr.replaceAll("[1-9]\\d*", ".{$0}"));
3     }

微笑脸…………:) 

大概也就差了一个次元吧

posted @ 2016-10-15 01:39  warmland  阅读(326)  评论(0编辑  收藏  举报