Leetcode——91. Decode Ways
来源:互联网 发布:做藏头诗的软件 编辑:程序博客网 时间:2024/05/17 11:04
#
https://leetcode.com/problems/decode-ways/?tab=Solutions
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.
#
动态规划问题:递推公式为
DP问题:dp[i+2]=s[i,i+1]<=26?2*dp[i]:dp[i]
dp[i]表示到i位置,可能的解码顺序。
可是这一题需要考虑300,00,这种有0出现的情况,这些边边角角真TM烦人!
本来十来行代码,现在为了检查意外情况一下子变成几十行了!
class Solution {//DP问题:dp[i+2]=(s[i,i+1]<=26?2*dp[i]:dp[i])public: int numDecodings(string s) { if(s.length()==0) return 0; int *dp=new int[s.length()]; int *num=new int[s.length()]; for(int i=0;i<s.length();i++) { num[i]=s[i]-'0'; } //合理性检查,排除30,00这种数的出现 if(num[0]==0) return 0; else for(int i=1;i<s.length();i++) { if((num[i]==0&&num[i-1]>=3)||(num[i]==0&&num[i-1]==0)) return 0; else continue; } dp[0]=1; if(s.length()>=2) { int temp=num[0]*10+num[1]; if(temp<=26&&num[1]!=0) dp[1]=2; else dp[1]=1; } for(int i=2;i<s.length();i++) { if(num[i-1]==0)//前面的判断已经保证不会出现00 dp[i]=dp[i-1]; else if(num[i]==0) { if(num[i-1]<3)//出现20这种 dp[i]=dp[i-2]; else return 0; } else { int temp=num[i-1]*10+num[i]; if(temp<=26) dp[i]=dp[i-1]+dp[i-2]; else dp[i]=dp[i-1]; } } return dp[s.length()-1]; }};
0 0
- Leetcode——91. Decode Ways
- LeetCode —— Decode Ways
- LeetCode——Decode Ways
- leetcode——Decode Ways
- leetcode笔记—Decode Ways
- Leetcode 91. Decode Ways&&639.Decode ways
- [Leetcode] 91. Decode Ways
- LeetCode --- 91. Decode Ways
- [LeetCode]91.Decode Ways
- [leetcode] 91.Decode Ways
- [leetcode] 91. Decode Ways
- Leetcode 91. Decode Ways
- leetcode 91. Decode Ways
- Leetcode 91. Decode Ways
- leetcode 91. Decode Ways
- LeetCode 91. Decode Ways
- LeetCode *** 91. Decode Ways
- Leetcode:91. Decode Ways
- [Unity3D]-协程的介绍和使用
- oracle 存储过程的例子
- Asteroids(二分图匹配)
- 记录一下误删除了mysql表中的数据后的恢复过程
- CSDN博客发布测试
- Leetcode——91. Decode Ways
- Python生成词云的制作
- [分块] [BZOJ2724] [Violet 6] 蒲公英
- (OK) 移植,编译,安装 LineageOS-14.1-kiwi (Android-7.1.1,运行在Huawei honor 5x) for VirtualBox
- 网络摄像机IPCamera RTSP直播播放网络/权限/音视频数据/花屏问题检测与分析助手EasyRTSPClient
- Meterial Design最佳体验(1): 使用Toolbar, CoordinatorLayout, AppBarLayout等实现精美标题栏
- tp框架中const的设置问题
- 258. Add Digits
- hdu-6015map容器的应用