这道题目的思路和上一篇博客中求ClimbingStairs的求解过程类似,把字符串看作是台阶,不同的数字组合看作是每次攀爬台阶的种数,求解所有字符串中数字的译码方式。在ClimbingStairs中每次攀爬都是1种或2种方式,而在DecodeWays中需要多加入几个逻辑判断,只有在某些情况下才会有两种译码方式,解题思路在代码注释中给出。
package LeetCode_chz;
import java.util.Scanner;
/**
* @题目描述: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.
* @解题思路:该问题的解决和斐波那契数列求F(n)类似,只是多加了一些判断。该题采用的思想是迭代统计。
* 1、如果(i-1)为0,则i为0中译码方式;
* 2、 a)如果字符串只有一位,则译码方式为1,
* b)如果字符串大于1位,且(i-2)位不是1,则i处译码方式为1种,即a=0,b=1求和累加
* c)如果字符串大于1位,且(i-2)位不是2,或者(i-1)位不是0-6的数字,则i处的译码方式为1种,即a=0,b=1,累加
* 3、其他情况下(i-1和i-2处的字符为3-9):则译码方式只有a+b种,其中a为temp。
* @author 崔洪振367
* @version 创建时间:2017年4月24日 下午6:28:42
*/
public class Q090_DecodeWays {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
String string = scanner.next();
System.out.println(decodeways(string));
}
scanner.close();
}
public static int decodeways(String string){
//合法性判断
if(string == null || string.length() ==0 || string.charAt(0) == '0'){
return 0;
}
int a = 0;//迭代实现的前一个记录
int b = 1;//迭代实现的当前一个记录
//长度为n的字符串有n+1个阶
int len = string.length()+1;
for(int i=1; i<len; i++){
if(string.charAt(i-1) == '0')
b = 0;
if(i<2 || !(string.charAt(i-2) == '1' || (string.charAt(i-2) == '2' && string.charAt(i-1) <= '6'))){
a = 0;//不满足条件的decode有0种方式
}
int temp = b;
b += a;
a = temp;
}
return b;
}
}