fork(4) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import java.util.stream.Collectors;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone {
  9. private static final String[] keys;
  10. private static final String[] values;
  11.  
  12. static {
  13. String alphabet = "abcdefghijklmnopqrstuvwxyz";
  14. keys = new String[alphabet.length()];
  15. values = new String[alphabet.length()];
  16. for (int i = 0; i < alphabet.length(); i++) {
  17. keys[i] = String.valueOf(i + 1);
  18. values[i] = alphabet.substring(i, i + 1);
  19. }
  20. }
  21.  
  22.  
  23. public static List<String> decode(String input) {
  24. List<String> results = new ArrayList<>();
  25. decodeRecursive(input, "", results);
  26. return results;
  27. }
  28.  
  29. private static void decodeRecursive(String input, String current, List<String>results) {
  30. if (input.length() == 0) {
  31. results.add(current);
  32. return;
  33. }
  34.  
  35. for (int i = 0; i < keys.length; i++) {
  36. String key = keys[i];
  37. if (input.startsWith(key)) {
  38. decodeRecursive(input.substring(key.length()), current + values[i], results);
  39. }
  40. }
  41. }
  42.  
  43. public static void main(String[] args) {
  44. for (String encoded : new String[]{"1123", "123456"}) {
  45. String decoded = decode(encoded).stream().collect(Collectors.joining("\n "));
  46. System.out.printf("Input %s decodes as:\n %s\n", encoded, decoded);
  47. }
  48. }
  49. }
Success #stdin #stdout 0.19s 3359744KB
stdin
Standard input is empty
stdout
Input 1123 decodes as:
  aabc
  aaw
  alc
  kbc
  kw
Input 123456 decodes as:
  abcdef
  awdef
  lcdef