Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Created October 13, 2013 21:32
Show Gist options
  • Save charlespunk/6967665 to your computer and use it in GitHub Desktop.
Save charlespunk/6967665 to your computer and use it in GitHub Desktop.
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.
public class Solution {
public int numDecodings(String s) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(s == null || s.equals("")) return 0;
int[] dp = new int[s.length() + 1];
for(int i = 0; i < s.length(); i++) dp[i] = -1;
dp[s.length()] = 1;
return countDecode(s, 0, 0, true, dp);
}
public int countDecode(String s, int pos, int last, boolean start, int[] dp){
if(pos == s.length()){
if(start) return 1;
else return 0;
}
int thisNum = s.charAt(pos) - 48;
if(start){
int sum = 0;
if(thisNum <= 2 && thisNum >= 1)
sum += countDecode(s, pos + 1, thisNum, false, dp);
if(thisNum <= 9 && thisNum >= 1){
int count = 0;
if(dp[pos + 1] != -1){
count = dp[pos + 1];
}
else{
count = countDecode(s, pos + 1, thisNum, true, dp);
dp[pos + 1] = count;
}
sum += count;
}
return sum;
}
else{
int now = last * 10 + thisNum;
if(now <= 26 && now >= 10){
int count = 0;
if(dp[pos + 1] != -1) count = dp[pos + 1];
else {
count = countDecode(s, pos + 1, 0, true, dp);
dp[pos + 1] = count;
}
return count;
}
else return 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment