首页 > 代码库 > [LeetCode] Decode Ways(DP)
[LeetCode] Decode Ways(DP)
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.
就是要注意0的出现
class Solution {public: int numDecodings(string s) { int len = s.size(); if(len==0) return 0; vector<int> num(len,0);//第i个位置记录从s的第0个位置开始到第i个位置共有几种解码方式 if(len>=1 && s[0]==‘0‘) return 0; num[0] = 1; if(len==1) return num[0]; string s0 = s.substr(0,2); int d = sToInt(s0); int n=0; if(d>10 && d<=26 && d!=20) num[1] = 2; else if((s[1] ==‘0‘ && (s[0]==‘1‘|| s[0]==‘2‘))||s[1]!=‘0‘) num[1] = num[0]; else return 0; for(int i=2;i<len;i++){ if(s[i-1]==‘0‘){ if(s[i]!=‘0‘){ num[i] = num[i-1]; continue; } else return 0; } s0 = s.substr(i-1,2); d = sToInt(s0); if(s[i]==‘0‘){ if(d==10 || d==20){ num[i] = num[i-2]; continue; } else return 0; } if(d>10 && d<=26 ) num[i] = num[i-1]+num[i-2]; else num[i] = num[i-1]; }//end for return num[len-1]; }private: int sToInt(string s){ istringstream is(s); int d; is>>d; return d; }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。