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

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
    }

 

标签:Word,charAt,int,return,Abbreviation,Valid,abbr,&&,word
来源: https://www.cnblogs.com/feiflytech/p/15862406.html