【LeetCode】91. Decode Ways
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.
主要思路如下:
第i个位置就只依赖于其前最多两个位置(pre2, pre1)的值。
s[i]与s[i-1]无法构成组合时,s[i]自己玩自己的,解码数目不变(pre1种)。
s[i]与s[i-1]能够成组合时,解码数目就分为两部分:s[i-1]s[i]组合(pre2种) + s[i]自己玩自己的(pre1种)
有一些细节要注意:
1、不能以0开头
2、不能连续的0
3、不能有无法组合的0(比如304)
class Solution { public: int numDecodings(string s) { if(s.size() == 0) return 0; else if(s.size() == 1) { if(s[0] >= '1' && s[0] <= '9') return 1; else return 0; } // to here, s.size() >= 2 if(s[0] == '0') // cannot begin with '0' return 0; int pre2 = 1; int pre1 = 1; int ret = 0; for(int i = 1; i < s.size(); i ++) { if(s[i-1] == '0') { if(s[i] == '0') return 0; else ret = pre1; } else if(s[i-1] == '1') { if(s[i] == '0') ret = pre2; else ret = (pre1 + pre2); } else if(s[i-1] == '2') { if(s[i] == '0') ret = pre2; else if(s[i] >= '1' && s[i] <= '6') ret = (pre1 + pre2); else ret = pre1; } else { if(s[i] == '0') return 0; else ret = pre1; } pre2 = pre1; pre1 = ret; } return ret; } };