leetCode练习(91)

来源:互联网 发布:为什么美工工资高 编辑:程序博客网 时间:2024/05/09 16:33

题目:Decode Ways

难度:medium

问题描述:

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.

解题思路:使用动态规划的方法。从str.length=1开始一直计算到length=n. 其中,count[n]与count[n-1]和count[n-1]有关。具体情况有:

char[I]=0时,char[I-1]大于2或者等于0,无解count[I]=0 。char[I-1]=1或2时,count[I]=count[I-2].

char[I]!=0时,sum=10*char[I-1]+char[I]; 如果sum>26或者sum<10,count[I]=count[I-1].否则 count[I]=count[I]+count[I-1]。

具体代码如下:

public static int numDecodings(String s) {if(s==null||s.equals("")){return 0;}if(s.length()==1){return s.equals("0")?0:1;}        int len=s.length();         int lasttwo,lastone;        int temp;        int lastchar=s.charAt(0)-'0';        int sum;        if(lastchar==0){        return 0;        }                if(s.charAt(1)=='0'){        if(lastchar>2){        return 0;        }else{        lasttwo=1;        lastone=1;        }        }else{        sum=lastchar*10+s.charAt(1)-'0';        if(sum>26){        lasttwo=1;        lastone=1;        }else{        lasttwo=1;        lastone=2;        }        }        lastchar=s.charAt(1)-'0';        for(int i=2;i<len;i++){        temp=s.charAt(i)-'0';        if(temp==0){        if(lastchar>2||lastchar==0){        return 0;        }else{        lastchar=temp;        int a=lasttwo;        lasttwo=lastone;        lastone=a;        }        }else{        sum=lastchar*10+temp;        if(sum<10||sum>26){        lastchar=temp;        lasttwo=lastone;        //lastone 不变        }else{        lastchar=temp;        int a=lasttwo;        lasttwo=lastone;        lastone=a+lastone;        }        }        }        return lastone;    }



0 0
原创粉丝点击