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个数字(即长度)的解码数。0个数字的解码数是1,就是没得解。dp[i]计算是两种方式之和,如果当前末尾数(因为i是长度,这里就是第i-1个数)大于0,那它可以单独解码成一个字母;如果当前末尾数能和它前面一个数组成一个在10~26区间内的数,它俩合并也能解码。 corner case: s首位是0的话直接return0 two digits的case从i>1开始 用法: char to int 直接c-‘0’ string to int stoi(s) 实现:
class Solution { public: int numDecodings(string s) { if(s.empty() || s[0] == '0') return 0; int n = s.size(); vector<int> dp(n+1, 0); dp[0] = 1; for (int i=1; i<=n; i++){ if (s[i-1]-'0' > 0) dp[i] += dp[i-1]; if (i > 1 && 10 <= stoi(s.substr(i-2, 2)) && stoi(s.substr(i-2, 2)) <=26) dp[i] += dp[i-2]; } return dp[n]; } };