Skip to content

Instantly share code, notes, and snippets.

@bittib
Created June 2, 2013 15:18
Show Gist options
  • Save bittib/5693820 to your computer and use it in GitHub Desktop.
Save bittib/5693820 to your computer and use it in GitHub Desktop.
Decode Ways
/*
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.
*/
// O(n) DP
public int numDecodings(String s){
if (s == null || s.length() == 0 || s.charAt(0) == '0') return 0;
int n = s.length();
int[] f = new int[n+1];
f[0] = 1;
f[1] = 1;
for (int i=2; i<=n; i++){
char prev = s.charAt(i-2), ch = s.charAt(i-1);
if (ch == '0'){
if (prev != '1' && prev !='2') return 0;
f[i] = f[i-2];
}else{
f[i] = f[i-1];
if (prev == '1' || (prev == '2' && ch <= '6'))
f[i] += f[i-2];
}
}
return f[n];
}
// Space : O(1) Solution
public static int numDecodings(String s){
if (s == null || s.length() == 0 || s.charAt(0) == '0') return 0;
int p2 = 1, p1 = 1, p0 = 1, n = s.length();
for (int i=1; i<n; i++, p2 = p1, p1 = p0){
if(s.charAt(i) == '0'){
if (s.charAt(i-1) != '1' && s.charAt(i-1) != '2')
return 0;
p0 = p2;
}else{
p0 = p1;
if (s.charAt(i-1) == '1' || (s.charAt(i-1) == '2' && s.charAt(i) <= '6'))
p0 += p2;
}
}
return p0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment