二刷91. Decode Ways

Medium
第一种是常规动归, 空间复杂度O(N),前几遍写出来几个bug. 一是initialize dp[0] = 1, 二是状态转移方程都是 += dp[i-1] 或是 += dp[i-2]

class Solution {
    public int numDecodings(String s) {
        if (s == null || s.length() == 0 || s.equals("0")){
            return 0;
        }
        int n = s.length();
        int[] dp = new int[n+1];
        dp[0] = 1;
        if (s.charAt(0) != '0'){
            dp[1] = 1;
        } else {
            return 0;
        } 
        for (int i = 2; i < n + 1; i++){
            int oneDigit = s.charAt(i-1) - '0';
            if (oneDigit >= 1 && oneDigit <= 9){
                dp[i] += dp[i-1];
            } 
            int twoDigits = Integer.parseInt(s.substring(i-2, i));
            if (twoDigits >= 10 && twoDigits <= 26){
                dp[i] += dp[i-2];
            }
        }
        return dp[n];
    }
}

然后是优化到space O(1), 注意一下每次循环reset curt = 0比较好做

class Solution {
    public int numDecodings(String s) {
        if (s == null || s.length() == 0 || s.equals("0")){
            return 0;
        }
        int prevOne = 0;
        int prevTwo = 0;
        int curt = 0;        
        if (s.charAt(0) != '0'){
            curt = 1;
            prevOne = curt;
            prevTwo = prevOne;
        } 
        for (int i = 1; i < s.length(); i++){
            curt = 0;
            int oneDigit = s.charAt(i) - '0';
            if (oneDigit >= 1 && oneDigit <= 9){
                curt += prevOne;
            } 
            int twoDigits = Integer.parseInt(s.substring(i-1, i+1));
            if (twoDigits >= 10 && twoDigits <= 26){
                curt += prevTwo;
            }
            prevTwo = prevOne;
            prevOne = curt;
        }
        return curt;
    }
}

你可能感兴趣的:(二刷91. Decode Ways)