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.
class Solution { int fibnacci_sum(int n) { if (n == 0) return 1; if (n == 1) return 1; if (n == 2) return 2; return fibnacci_sum(n - 1) + fibnacci_sum(n - 2); } public: int numDecodings(string s) { if (s.empty()) return 0; if (s.length() == 1) { if (s[0] != '0') return 1; return 0; } int k = 0; int nums = 1; while (k + 1 < s.length()) { if (s[0] == '0') return 0; k = 0; while (k + 1 < s.length()) { if (s[k] >= '3') { nums *= fibnacci_sum(k+1); s.erase(0, k + 1); k = 0; break; } if (s[k] == '0') { nums *= fibnacci_sum(k - 1); s.erase(0, k + 1); k = 0; break; } if (s[k] == '2'&&s[k + 1] > '6') { nums *= fibnacci_sum(k + 1); s.erase(0, k + 1); k = 0; break; } k++; } } if (s.length() > 1) { if (s[k] >= '3') nums *= fibnacci_sum(k+1); else if (s[k] == '0') nums *= fibnacci_sum(k - 1); else nums *= fibnacci_sum(s.length()); return nums; } if (s.empty()) return nums; if (s[0] == '0') return 0; return nums; } };