408. Valid Word Abbreviation --字符串处理

Given s = "internationalization", abbr = "i12iz4n":

Return true.

abbr 里数字代表相应的字符数,问字符串是否相等

虽然是一个easy 的题但却有两个坑:
1. abbr 结尾的地方是数字 例如:
s= "internationalization" abbr= "i5a11o1" , 因此 return时得加上cout 来判断 index + Integer.valueOf(count)
2.字符中 有 0, 例如 s= "a" abbr= "01" 因此只要出现一个不是其他数字后面的0 都是非法的, 比如 01 非法, 而10 合法。加上这个判断
  if(count.equals("0") && c=='0') return false;
 
class Solution {
    public boolean validWordAbbreviation(String word, String abbr) {
        int index = 0;
        String count = "0";
        for(int i=0; i<abbr.length(); i++){
            char c = abbr.charAt(i);  
            if(Character.isLetter(c) ) {
                index = index + Integer.valueOf(count);
                if(index >= word.length() || c != word.charAt(index) ) return false;
                count = "0";
                index++;
            }  
            else {
                if(count.equals("0") && c=='0') return false;
                count += c;
               
            }
        }
    
        return index + Integer.valueOf(count) == word.length();
    }
}

猜你喜欢

转载自www.cnblogs.com/keepAC/p/9945943.html