91.解码方法

题目:

https://leetcode-cn.com/problems/decode-ways/

解码方法

  1. 例子:121013271

  2. 状态方程

(1) 如果S[i] == 0

① 如果(S[i-1] ==1 || S[i-1] ==2)dp[i]=dp[i-2]

“110”->”1,2,1”

② 否则返回0

(2) 如果(S[i-1]==2) &&(s[i] <=6),dp[i]=dp[i-1]+dp[i-2]

(3) 如果S[i-1] == 1无论S[i]是多少,dp[i]=dp[i-1]+dp[i-2]

    3. 边界

(1) Dp[0]=1,dp[-1]=1

  4. 程序

public static int numDecodings(String s) {
       if(s.length() == 0 || s == null || s.charAt(0)=='0'){
            return 0;
        }
        char[] arr = s.toCharArray();
        int[] arrInt = new int[arr.length];
        for(int i = 0 ; i < arr.length ; i ++){
            arrInt[i] = arr[i] - '1' + 1;
        }
        int num1 = 1,num2 = 1;
        int tmp = 1;
        for(int i = 1 ;i < arrInt.length ; i ++){
            tmp = num2;
            if(arrInt[i] == 0){
                if( arrInt[i-1] != 1 && arrInt[i-1]!=2)
                    return 0;
                else{
                    tmp = num1;
                }
            }else{
                if(arrInt[i-1]==1){
                    tmp = num1 + num2;
                }
                if(arrInt[i-1]==2 && arrInt[i] <= 6){
                    tmp = num1 + num2;
                }
            }

            num1=num2;
            num2 = tmp;
        }
        return tmp;

    }

 

你可能感兴趣的:(91.解码方法)