91. Decode Ways

来源:互联网 发布:游光网络账号注册 编辑:程序博客网 时间:2024/06/07 05:19

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.

思路: 当0出现在首位的时候,不是正常的,返回0; 当前的可能等于其前一位的可能数+前2位的数,当满足一点的条件下。

<span style="font-size:14px;">public class Solution {    public int numDecodings(String s) {        int n=s.length();        if(n<=0||s.charAt(0)=='0')            return 0;        if(n==1){                return 1;        }                int p1=1,p2=1,cur=0;        for(int i=1;i<n;i++){            cur=0;            int first=s.charAt(i)-'0';            if(first>=1&&first<=9)                cur=p1;            int second=first+10*(s.charAt(i-1)-'0');            if(second<=26&&second>=10){                cur+=p2;            }                        p2=p1;            p1=cur;        }        return cur;            }   }</span>


0 0
原创粉丝点击