LeetCode-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 an encoded message containing digits, determine the total number of ways to decode it.

For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).

The number of ways decoding "12" is 2.

当可以把连续两个数字合起来或分开时 总数f=fi-1+fi-2

只能合起来时f=fi-2

只能分开时f=fi-1

class Solution {
public:
    int numDecodings(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(s.length()==0)return 0;
        if(s[0]=='0')return 0;
        else if(s.length()==1){
            if(s[0]!='0')return 1;
            else return 0;
        }
        int f1=1,f2,f;
        if(s[1]=='0'){
            if(s[0]!='1'&&s[0]!='2')return 0;
            f2=1;
        }
        else{
            if(s[0]=='1'||s[0]=='2'&&s[1]>='1'&&s[1]<='6')f2=2;
            else f2=1;
        }
        for(int i=2;i<s.length();i++){
            if(s[i]=='0'){
                if(s[i-1]!='1'&&s[i-1]!='2')return 0;
                f=f1;
            }
            else{
                if(s[i-1]=='1'||s[i-1]=='2'&&s[i]>='1'&&s[i]<='6')f=f1+f2;
                else f=f2;
            }
            f1=f2;
            f2=f;
        }
        return f2;
    }
};
原文地址:https://www.cnblogs.com/superzrx/p/3332306.html