FTPrep, 91 Decode Ways, TODO: need to repeat and conclude

来源:互联网 发布:淘宝分流比例设置 编辑:程序博客网 时间:2024/06/13 12:10

这道题,也很蛋疼。明明是要考DP,但是还要加复杂的判断条件。所以解题时不是很顺。

题目提供了一个encoding的规则,从字母到数字,现在给数字,要来generate string,给出多少种这样的方式。TODO,integer to roman,roman to integer 归于一类。

代码:

public class Solution {    public int numDecodings(String s) {        int len=s.length();        if(len==0) return 0;        if(s.charAt(0)=='0') return 0;  // 0是special case,所以要做特殊考虑        if(len==1) return 1;                int num1=1; // # of ways for the previous index (i-1), and the current digit can only be intepreted in 1 way        int num2=1; // # of ways for the previous index (i-1) + the current digits can be interpreted in an additional way        for(int i=1; i<len; i++){            int num=0;            if(s.charAt(i)=='0'){  // 0 is a special case, only valid if 10, 20                if(s.charAt(i-1)=='1' || s.charAt(i-1)=='2') num=num1;                else return 0;             }            else if(s.charAt(i-1)=='1' || (s.charAt(i-1)=='2' && s.charAt(i)<'7')) num=num1+num2; // the only case that num = num1 + num2 are 11-19, and 20-26            else num=num2;                        num1=num2;            num2=num;        }        return num2;    }}




原创粉丝点击