Total Accepted: 55559 Total Submissions: 331659 Difficulty: Medium
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) { int size = s.size(); int a =0,b=1; for(int i=size-1;i>=0;i--){ if(i==size-1){ a = s[i]=='0'? 0:1; }else{ int num = (s[i]-'0')*10+(s[i+1]-'0'); int tmp = b; s[i] == '0' ? (b=a,a=0) : (num<=26 ? b=a,a+=tmp : b=a); } } return a; } };