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.
Have you met this question in a real interview?
思路: 用 dp 来存储 ways, 如果 为 0 , 就断开 ,设置成 0 , 每次 ways[i] = ways[ i - 1] , 然后加上 如果前两位能和成 一个合法数字的,
思路 2: space o(1) 解法, 其实就是只利用 奇偶位的交叉相加。 & 1 其实就是 %2 一样。
易错点 : 主要要检查前两位, 所以要把 i = 0 单独算。 注意要 ways[i] += ways [i - 2];
注意两种解法的 起始点的设置 和 test case : 110 的情况。
public class Solution {
public int numDecodings(String s) {
int len = s.length();
if(len < 1)
return 0;
int[] ways = new int[len + 1];
ways[0] = 1;
if(s.charAt(0) == '0'){//----因为下面要检查前两位
ways[1] = 0;
}else{
ways[1] = ways[0];
}
for(int i = 2; i <= len; i++){
if(s.charAt(i - 1) == '0'){
ways[i] = 0;
}else{
ways[i] = ways[i - 1];
}
if(s.charAt(i - 2) == '1' || (s.charAt(i - 2) == '2' && s.charAt(i - 1) <= '6')){//---
ways[i] += ways[i - 2];// ---- 记住是 i - 2
}
}
return ways[len];
}
}
public class Solution {
public int numDecodings(String s) {
if(s.length() < 1)
return 0;
int[] ways = new int[2];
ways[(s.length() - 1) & 1] = s.charAt(s.length() - 1) == '0' ? 0 : 1;
ways[s.length() & 1] = 1;
for(int i = s.length() - 2; i >= 0; i--){
if(s.charAt(i) != '0'){
if(s.charAt(i) == '1' || (s.charAt(i) == '2' && s.charAt(i + 1) <= '6')){
ways[i & 1] += ways[(i + 1) & 1];
}else{
ways[i & 1] = ways[(i + 1) & 1];
}
}else{
ways[i & 1] = 0;
}
}
return ways[0];
}
}