Created
February 18, 2014 05:14
-
-
Save rayjcwu/9064996 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
| class Node { | |
| char c; | |
| Set <Node> children; | |
| } | |
| class PrefixGrouper { | |
| ArrayList <String> result = new ArrayList<String>(); | |
| public ArrayList<String> prefixWith(Node root, String prefix) { | |
| result.clear(); | |
| char []p = prefix.toCharArray(); | |
| Stack <Character> stack = new Stack<Character>(); | |
| prefixWith(root, p, 0, stack); | |
| return result; | |
| } | |
| private ArrayList<String> prefixWith(Node node, char [] prefix, int i, Stack<Character> stack) { | |
| if (i < prefix.length && node != null) { | |
| if (node.children(contains(new Node(prefix[i])))) { | |
| stack.add(node.c); | |
| prefixWith(node, prefix, i + 1, stack); | |
| } | |
| } else if (node.children.size() == 0) { | |
| StringBuilder sb = new StringBuilder(); | |
| for (char c: Collections.reverse(stack)) { | |
| sb.append(c); | |
| } | |
| result.append(sb.toString()); | |
| } else { | |
| for (Node n: node.children) { | |
| stack.add(n.c); | |
| prefixWith(node, prefix, i, stack); | |
| stack.remove(); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment