leetcode [91]Decode Ways

A message containing letters from A-Z is being encoded to numbers using the following mapping:

'A' -> 1
'B' -> 2
...
'Z' -> 26

Given a non-empty string containing only digits, determine the total number of ways to decode it.

Example 1:

Input: "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).

Example 2:

Input: "226"
Output: 3
Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).

题目大意:

找出给定数字字符串可能对应的字母字符串的总数。

解法:

我觉得这是一道动态递归的题目,假设dp[i]对应的是数字字符串i位置上可能的个数,那么dp[i]要么等于dp[i-1],要么等于dp[i-1]+dp[i-2]的值。

当s[i-1:i]的值在10到26之间,那么 dp[i]=dp[i-1]+dp[i-2],

当不是的时候,那么dp[i]=dp[i-1]。

还要分析当s[i]='0'的时候,这个时候i不能等于0,而且是s[i]只能和s[i-1]组成字符串,字符串还要在给定范围内[10,26],要不然返回0,满足要求则dp[i]=dp[i-2]。

这里不用使用dp数组,而是使用三个变量保存dp[i-2],dp[i-1],dp[i]就可以了。

java:

class Solution {
    public int numDecodings(String s) {
        if(s.isEmpty()) return 0;
        if(s.length()>=1 && s.charAt(0)=='0') return 0;
        int a=1,b=1,c=1;
        for(int i=0;i<s.length();i++){
            int n=0;
            if(s.charAt(i)<'0'&&s.charAt(i)>'9') return 0;
            if(s.charAt(i)=='0'){
                if(s.charAt(i-1)<'1'||s.charAt(i-1)>'2') return 0;
                else c=a;
                continue;
            }
            if(i>0) n=Integer.parseInt(s.substring(i-1,i+1));
            if(i>0 && n>9 && n<27) c=a+b;
            else c=b;
            a=b;
            b=c;
        }
        return c;
    }
}

  

猜你喜欢

转载自www.cnblogs.com/xiaobaituyun/p/10676737.html