https://leetcode.com/problems/decode-ways/
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,ways[i] += ways[i-1], 最后两个数的范围只要在10-26间,ways[i] += ways[i-2],这里一定要注意,两个数的时候不能在1-26间,因为‘01’之类的数会满足这个条件,但是其实不是正确decode方法。
public class Solution {
public int numDecodings(String s) {
if(s==null || s.length()==0) return 0;
int[] ways = new int[s.length()+1];
ways[0] = 1;
int val = Integer.parseInt(s.substring(0, 1));
if(val != 0) ways[1] = 1;
else return 0;
for(int i=2; i<=s.length(); i++){
ways[i] = 0;
val = Integer.parseInt(s.substring(i-2, i));
if(val >=10 && val<=26){
ways[i] += ways[i-2];
}
val = Integer.parseInt(s.substring(i-1, i));
if(val != 0){
ways[i] += ways[i-1];
}
}
return ways[s.length()];
}
}
本文详细介绍了如何使用动态规划解决编码问题,通过LeetCode中的实例来展示了解码方法的实现过程及核心思想。重点讨论了如何通过状态转移方程来计算不同长度字符串的所有可能解码方式。
547

被折叠的 条评论
为什么被折叠?



