Simple JAVA solution


  • 1
    C
    public class Solution {
        
        public int numDecodings(String s)
        {
            if(null == s || s.length() == 0 || s.startsWith("0"))
            {
                return 0;
            }
            
            if(s.length() == 1)
            {
                return 1;
            }
            
            int n = s.length();
            
            int[] dp = new int[n + 1];
            dp[0] = 1;
            dp[1] = Character.getNumericValue(s.charAt(0)) == 0 ? 0 : 1;
    
            for(int i = 2; i <= n; i++)
            {
                int firstValue = Character.getNumericValue(s.charAt(i - 2));
                int secondValue = Character.getNumericValue(s.charAt(i - 1)); 
                
                if(secondValue > 0)
                {
                    dp[i] = dp[i - 1];
                }
                
                if(firstValue > 0)
                {
                    int value = firstValue * 10  + secondValue;
        
                    if(value >= 1 && value <= 26)
                    {
                        dp[i] += dp[i - 2];
                    }
                }
                
            }
            return dp[n];
        }
        
    }

Log in to reply
 

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