408. Valid Word Abbreviation

This is two points problem, just concentrate and carefully deal with the characters, then the problem can be solved.

This is a very good problem for writing all kinds of edge test cases.

    public boolean validWordAbbreviation(String word, String abbr) {
        int m = word.length(), n = abbr.length();
        int i = 0, j = 0;
        while (i < m && j < n) {
            if (word.charAt(i) == abbr.charAt(j)) {
                i++;
                j++;
            } else {
                if (!Character.isDigit(abbr.charAt(j)) || abbr.charAt(j) == '0')
                    return false;
                else {
                    int start = j;
                    while (j < n && Character.isDigit(abbr.charAt(j))) {  //be careful, need ot add a j < n, otherwise, eg. abbr="a1" will fail
                        j++;
                    }
                    int len = Integer.valueOf(abbr.substring(start, j));
                    i += len;
                }
            }
        }
        return i == m && j == n;  //if simply return true, eg. word = "a", abbr="2" will fail
    }

 

上一篇:1216. Valid Palindrome III


下一篇:python的几种序列化方式