【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).

这道题的关键在于把情况分好:

1.s[i]==0时:有两种情况

(1):s[i-1]=='1'||s[i-1]=='2',此时s[i]只能和前一个数字组合,例如120。此时A[i]=A[i-2]

(2):其他情况,s[i-1]>2,由于s[i]==0,所以此时不能组成组合,直接返回0;

2.s[i]<='6'&&s[i-1]=='1'||s[i-2]=='2':

此时s[i]既可以独立存在,也可以跟前一个结合。所以A[i]=A[i-1]+A[i-2]

3.其他情况,即s[i]!=0,并且情况2也不成立,此时s[i]只能独立存在。如131。A[i]=A[i-1]

谢谢这位博主,参考

class Solution {
public:
    int numDecodings(string s) {
        int length = s.size();
        if(length == 0) return 0;
        
        int cur=s[0]=='0'?0:1;
        int last = 1;
        
        for(int i=1;i<length;i++){
            int tem = cur;
            if(s[i]=='0'){
                if(s[i-1]=='1'||s[i-1]=='2')
                    cur = last;
                else 
                    return 0;
            }
            else if(s[i-1]=='1'||s[i-1]=='2'&&s[i]<='6'){
                cur += last;
            }
            else 
                cur = cur;
            
            last = cur;
        }
        return cur;
    }
};

猜你喜欢

转载自blog.csdn.net/poulang5786/article/details/81320784