Java DP clean and easy solution


  • 2
    A
    public class Solution {
        public int numDecodings(String s) {
            int len = s.length();
            if (len == 0) return 0;
            int[] dp = new int[len+1];
            dp[0] = 1;
            dp[1] = s.charAt(0) == '0' ? 0 : 1;
            for (int i=2; i<=len; i++) {
                char c0 = s.charAt(i-1);
                char c1 = s.charAt(i-2);
                if (c0 != '0')
                    dp[i] += dp[i-1];
                if (c1 == '1' || (c1 == '2' && c0 <= '6'))
                    dp[i] += dp[i-2];
            }
            return dp[len];
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.