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 { public: int numDecodings(string s) { if(s.empty() || s[0] == '0') return 0; int len = s.length(); if(len == 1) return check(s[0]); int fn = 0; int fn1 = 1; int fn2 = check(s[0],s[1]) + check(s[1]); for(int i=2; i<len; i++) { if(check(s[i])) fn += fn2; if(check(s[i-1],s[i])) fn += fn1; fn1 = fn2; fn2 = fn; fn = 0; } return fn2; } int check(char x) { return (x != '0') ? 1:0; } int check(char x, char y) { return (x == '1' || x == '2' && y <= '6') ? 1:0; } };