Intuitive Java DP


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

Log in to reply
 

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