1ms concise DP solution(Java)


  • 0
    L
    public class Solution {
        public int numDecodings(String s) {
            if(s.length() == 0) return 0;
            char[] c = s.toCharArray();
            int[] dp = new int[c.length + 1];
            dp[0] = 1;
            for(int i = 1; i <= c.length; i++){
                if(c[i - 1] != '0')
                    dp[i] += dp[i - 1];
                if(i - 2 >= 0 && (c[i - 2] == '1' || (c[i - 2] == '2' && c[i - 1] >= '0' && c[i - 1] <= '6')))
                    dp[i] += dp[i - 2];
            }
            return dp[c.length];
        }
    }
    

Log in to reply
 

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