Skip to content

Instantly share code, notes, and snippets.

@rayjcwu
Created February 18, 2014 05:14
Show Gist options
  • Select an option

  • Save rayjcwu/9064996 to your computer and use it in GitHub Desktop.

Select an option

Save rayjcwu/9064996 to your computer and use it in GitHub Desktop.
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