Simple Java DP solution


  • 0
    R
    public class Solution {
        public int numDecodings(String s) {
            int n = s.length();
            if (n == 0) return 0;
            int[] dp = new int[n+1];
            dp[0] = 1;
            dp[1] = (s.charAt(0) == '0') ? 0 : 1;
            for (int i = 1; i < n; i++) {
                if (dp[i] > 0 && s.charAt(i) != '0'){
                    dp[i+1] += dp[i];
                }
                int test = Integer.parseInt(s.substring(i-1,i+1));
                if (dp[i-1] > 0 && test < 27 && test > 9){
                    dp[i+1] += dp[i-1];
                }
                if (dp[i+1] == 0) {
                    return 0;
                }
            }
            return dp[n];
        }
    }
    

Log in to reply
 

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