A-Z
is being encoded to numbers using the following mapping:
'A' -> 1 'B' -> 2 ... 'Z' -> 26Given 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.public class Solution {
public int numDecodings(String s) {
if(s==null || s.isEmpty() || s.startsWith("0")) {
return 0;
}
int ways[] = new int[s.length()+1];
ways[0] = 1;
for(int i=0;i<s.length();i++) {
if(s.charAt(i)!='0') {
ways[i+1] += ways[i];
}
if(i!=0 && Integer.parseInt(s.substring(i-1, i+1))==0) {
return 0;
}
if(i!=0 && Integer.parseInt(s.substring(i-1, i+1))<=26 && s.charAt(i-1)!='0') {
ways[i+1] += ways[i-1];
}
}
return ways[ways.length-1];
}
}
=========
public class Solution {
public int numDecodings(String s) {
if (s == null || s.length() == 0 || s.charAt(0) == '0') {
return 0;
}
int nPre2 = 0;
int nPre1 = 1;
int n = 0;
for (int i = 0; i < s.length(); i++) {
n = 0;
if (s.charAt(i) != '0') {
n = nPre1;
}
if (i != 0) {
int num1 = Integer.parseInt(s.substring(i - 1, i + 1));
if (num1 >= 10 && num1 <= 26) {
n += nPre2;
}
}
nPre2 = nPre1;
nPre1 = n;
}
return n;
}
}
没有评论:
发表评论