91. Decode Ways 數字轉字母的不同編碼方式
阿新 • • 發佈:2019-01-25
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"
"L"
(12).
The number of ways decoding "12"
is 2.
1. 看別人的 (這個我不會)
class Solution { public: bool isValid(char c){ return c <= '9' && c >'0'; } bool isvalid(char c1, char c2){ if(c1 == '1') return c2 <='9' && c2 >='0'; if(c1 == '2') return c2 <='6' && c2 >='0'; return false; } int numDecodings(string s) { int len = s.size(); if(len <= 0) return 0; vector<int>res(len+1,0); res[0] = 1; for(int i = 0; i < len; i++){ if(isValid(s[i])) res[i+1] += res[i]; if(isvalid(s[i-1],s[i])) res[i+1] += res[i-1]; } return res[len]; } };