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
Given encoded message
"12"
, it could be decoded as "AB"
(1 2) or "L"
(12).
The number of ways decoding
"12"
is 2.
Solution 1: from end to start will be easier. The key is that '0' can not be used independently.
public class Solution {
public int numDecodings(String s) {
int n=s.length();
if (n==0) return 0;
int pre=1, res=1;
for (int i=n-1; i>=0; i--) {
int temp=res;
if (s.charAt(i)=='0') res=0;
else if (i<n-1 && Integer.valueOf(s.substring(i,i+2))<=26) res+=pre;
pre=temp;
}
return res;
}
}
没有评论:
发表评论