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>
本文介绍了一种用于解码数字字符串的算法,该算法能够计算出一个由A到Z字母编码成数字的字符串的所有可能解码方式的数量。例如,对于字符串12,它可以被解码为AB或者L,因此该字符串有两种解码方式。

被折叠的 条评论
为什么被折叠?



