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.
字符A-Z用整数1-26编码,先给定一个数字串,问共有多少种解码情况
class Solution { public: bool isValid(string num){ if(num.length()==1 && num>="1" && num<="9")return true; if(num.length()==2 && num>="10" && num<="26")return true; return false; } int numDecodings(string s) { if(s.length()==0)return 0; if(s.length()==1){ if(isValid(s))return 1; else return 0;//如果第1位为0,不可能解码 } int *decodeWays = new int[s.length()]; //初始化解码到第1位的方案数 if(isValid(s.substr(0,1)))decodeWays[0]=1; else return 0; //初始化解码到第2位的方案数 decodeWays[1] = isValid(s.substr(1,1))?decodeWays[0]:0; decodeWays[1] += isValid(s.substr(0,2))?1:0; if(decodeWays[1]==0)return 0; //不存在解码到这一位的方案 //计算解码到第3~第s.length()位的方案数 for(int i=2; i<s.length(); i++){ decodeWays[i]=isValid(s.substr(i,1))?decodeWays[i-1]:0; decodeWays[i]+=isValid(s.substr(i-1,2))?decodeWays[i-2]:0; if(decodeWays[i]==0)return 0; //不存在解码到这一位的方案 } return decodeWays[s.length()-1]; } };
LeetCode: Decode Ways [090],布布扣,bubuko.com
原文:http://blog.csdn.net/harryhuang1990/article/details/27817961