Review an answer - Decode Ways

前端 未结 7 1262
隐瞒了意图╮
隐瞒了意图╮ 2021-01-31 19:36

I\'m trying to solve a question and my question here is why doesn\'t my solution work?. Here\'s the question and below\'s the answer.

Question taken fr

7条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-31 20:35

    Here is my code to solve the problem. I use DP , I think it's clear to understand.

    Written in Java

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

    }

提交回复
热议问题