Leetcode91. Decode Ways

这题题意稍稍有些不够明确。比如,遇到"01","80"等无法编码的,其实是返回0的。
想到了用dp,但是写的不太简洁,参考Solution,写一个简洁版:

public class Solution {
    public int numDecodings(String s) {
        if(s == null || s.length() == 0) {
            return 0;
        }
        int[] dp = new int[s.length()+1];
        dp[0] = 1;
        if(s.charAt(0)=='0') return 0;
        dp[1] = 1;
        for(int i = 2; i <= s.length(); i++) {
            int one = Integer.valueOf(s.substring(i-1, i));
            int two = Integer.valueOf(s.substring(i-2, i));
            if(one >= 1 && one <= 9) dp[i] += dp[i-1];  
            if(two >= 10 && two <= 26) dp[i] += dp[i-2];
        }
        return dp[s.length()];
    }
}

Runtime: 2 ms, faster than 46.38% of Java online submissions for Decode Ways.
Memory Usage: 37 MB, less than 21.42% of Java online submissions for Decode Ways.

posted @ 2019-04-23 15:42  大胖子球花  阅读(66)  评论(0)    收藏  举报