leetcode_Decode Ways
来源:互联网 发布:剑侠情缘3网游mac 编辑:程序博客网 时间:2024/06/14 10:55
描述:
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.
思路:
直接从后面开始算,如果str.substring(i,i+2)代表的数值小于26,那么,memo[i]=memo[i+1]+memo[i+2];否则,memo[i]=memo[i+1],虽然看起来很简单,却是很难想,一般都是从前面开始,然后比较字符的值再做判断,这样的话控制逻辑会非常复杂。
代码:
public int numDecodings(String s){int strLen=s.length();if(strLen==0)return 0;int memo[]=new int[strLen+1];memo[strLen]=1;memo[strLen-1]=s.charAt(strLen-1)!='0'?1:0;for(int i=strLen-2;i>=0;i--){if(s.charAt(i)=='0')continue;else {memo[i]=(Integer.parseInt(s.substring(i,i+2)))<=26?memo[i+1]+memo[i+2]:memo[i+1];}}return memo[0];}
0 0
- LeetCode_Decode Ways
- Leetcode_decode-ways
- leetcode_Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode ways
- Decode Ways
- FreeCMS怎么动态访问模板?
- [高考]18个文言虚词之"而"
- UNIX网络编程卷一:第十六章 非阻塞I/O
- 我们如何学好java
- Oracle数据库SQLPLUS中几个常用set语句
- leetcode_Decode Ways
- 程序员爱情表白专用html5动画网页的代码
- B - {A} + {B}
- 对象数组的使用
- Oracle整形转字符串to_char()
- A. Music(Codeforces Round #315 (Div. 2) 求最大的容纳量)
- 【SpringMVC整合MyBatis】springmvc异常处理-全局异常处理器开发
- 第84讲:Scala中List和ListBuffer设计实现思考
- 安卓拖动条