LeetCode 408 Valid Word Abbreviation

思路

遍历abbr字符串,遇到0~9的字符就开始统计计数存到num【corner case:遇到01这种带0前缀的要在这里直接去掉,返回false】,否则就将其与word中对应位置比较是否相同,这里对应位置可以使用一个index来确定:每次遇到非0~9时就移动
index = index+num,最后别忘了index还要自增一下。

复杂度

时间复杂度O(len(abbr)), 空间复杂度O(1)

代码

public class Solution {
    /**
     * @param word: a non-empty string
     * @param abbr: an abbreviation
     * @return: true if string matches with the given abbr or false
     */
    public boolean validWordAbbreviation(String word, String abbr) {
        // write your code here
        int num = 0;
        int index = 0;
        for(int i = 0; i < abbr.length(); i++) {
            if('0' <= abbr.charAt(i) && abbr.charAt(i) <= '9') {
                // "a" -- "01" : false
                if(num == 0 && abbr.charAt(i) == '0') return false;
                num *= 10;
                num += abbr.charAt(i) - '0';
            } else {
                index += num;
                num = 0;
                if(word.charAt(index) != abbr.charAt(i)) {
                    return false;
                }
                index++;
            }
        }
        if(num == 0) return true;
        if(num != 0 && index + num == word.length()) {
            return true;
        }
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36754149/article/details/88688769
408
今日推荐