Created
February 12, 2015 05:43
-
-
Save Siddhartha90/07b09ec7e86d1e1db948 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class decodingcountDP { | |
static int calls = 0; | |
static Map<Integer, String> codes = new HashMap<Integer, String>(); | |
private static void construct(){ | |
codes.put(1, "A"); | |
codes.put(2, "B"); | |
codes.put(3, "C"); | |
codes.put(4, "D"); | |
codes.put(5, "E"); | |
codes.put(6, "F"); | |
codes.put(7, "G"); | |
codes.put(8, "H"); | |
codes.put(9, "I"); | |
codes.put(10, "J"); | |
codes.put(11, "K"); | |
codes.put(12, "L"); | |
codes.put(13, "M"); | |
codes.put(14, "N"); | |
codes.put(15, "O"); | |
codes.put(16, "P"); | |
codes.put(17, "Q"); | |
codes.put(18, "R"); | |
codes.put(19, "S"); | |
codes.put(20, "T"); | |
codes.put(21, "U"); | |
codes.put(22, "V"); | |
codes.put(23, "W"); | |
codes.put(24, "X"); | |
codes.put(25, "Y"); | |
codes.put(26, "Z"); | |
} | |
private static int decode(String str){ | |
construct(); | |
int n = str.length(); | |
int []count = new int[n+1]; | |
count[0] = 1; | |
count[1] = 1; | |
for (int i =2; i<=n; i++){ | |
// If you have 0's, then they don't have a corresponding singular letter. Break off the recursion. | |
if (i+1 <=n) | |
if (str.substring(i, i+1).equals("0")) | |
continue; | |
String x = null; | |
if (i+1 <=n) | |
x = codes.get(Integer.parseInt(str.substring(i, i+1))); | |
if (x != null) | |
count[i] = count[i-1]; | |
// If it's more than 26, it doesn't have a corresponding letter. Break off the recursion. | |
if (i+2 <=n) | |
if (Integer.parseInt(str.substring(i, i+2)) <= 26) | |
count[i] += count[i-2]; | |
} | |
return count[n]; | |
} | |
public static void main(String[] args) { | |
System.out.println(decode(args[0])); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment