91. Decode Ways

public class Solution {
    public int numDecodings(String s) {
        if(s.length()==0) return 0;
        int[] dp=new int[s.length()+1];
        dp[s.length()]=1;
        dp[s.length()-1]= s.charAt(s.length()-1)!='0'? 1:0;
        for(int i=s.length()-2;i>=0;i--){
            if(s.charAt(i)=='0') continue;
            else dp[i]= (Integer.parseInt(s.substring(i,i+2))<=26)? dp[i+1]+dp[i+2]:dp[i+1];
        }
        return dp[0];
    }
}
public class Solution {
    public int numDecodings(String s) {
        int n1 =1, n2=1, n3=0;
        if(s.length()==0||s.charAt(0)=='0') return 0;
        for(int i=2; i<=s.length(); i++)
        {
            n3=0;
            if(s.charAt(i-1)!='0') n3=n2;
            int num = Integer.parseInt(s.substring(i-2,i));
            if(num>=10 && num<=26) n3+=n1;
            n1=n2;
            n2=n3;
        }
        return n2;
    }
}

你可能感兴趣的:(91. Decode Ways)