题目描述:
A message containing letters from A-Z
is being encoded to numbers using the following mapping:
'A' -> 1 'B' -> 2 ... 'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
Example 1:
Input: "12" Output: 2 Explanation: It could be decoded as "AB" (1 2) or "L" (12).
Example 2:
Input: "226" Output: 3 Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
中文理解:
给定一个映射关系,其中A-Z分别映射为1-26,给定一个数字构成的字符串,问映射为A-Z组成的字符串一共有多少种映射方法。
解题思路:
首先异常情况考虑,当首字符为0或者长度小于1时返回0;然后在遍历过程中,如果当前字符为0,看前面一个字符如果也为0或者大于2,则返回0,不是有效的字符序列;如果这个字符不为0,且前一个字符在是1或者2,则看当前字符构成的字符的整数是否在10-26之间,如果是的话,类似于斐波那契数列的相加迭代,如果不满足,则更新数值进行下一个字符判断。
代码(java):
class Solution {
public int numDecodings(String s) {
if(s.length()<1 || s.charAt(0)=='0')return 0;
int c1=1,c2=1,c3=0;
int len=s.length();
for(int i=0;i<len;i++){
if(s.charAt(i)=='0'){
if(s.charAt(i-1)=='0' || s.charAt(i-1)>'2'){
return 0;
}
else {
c3=c1;
}
}
else{
c3=c2;
if(i>0 && s.charAt(i-1)!='0' && (s.charAt(i-1)<'2' || s.charAt(i-1)=='2' && s.charAt(i)<='6')){
c3+=c1;
}
}
c1=c2;
c2=c3;
}
return c3;
}
}