shajibcse067
BAN USERimport java.util.ArrayList;
public class TrieNode {
char value;
ArrayList<TrieNode> children;
boolean isWord;
TrieNode(Character v) {
value = v;
children = new ArrayList<>();
}
void insert(String s) {
if (s == null || s.length() <= 0) {
isWord = true;
return;
}
char c = s.charAt(0);
for (TrieNode child : children) {
if (child.value == c) {
child.insert(s.substring(1));
return;
}
}
TrieNode newNode = new TrieNode(c);
children.add(newNode);
newNode.insert(s.substring(1));
}
void match(String prefix, String word) {
if (prefix == null || prefix.length() <= 0) {
getWords(word);
return;
}
char c = prefix.charAt(0);
String s=(prefix.length()>1)?prefix.substring(1):"";
for (TrieNode child : children) {
if (child.value == c)
child.match(s, word + c);
}
if (Character.isUpperCase(c)) {
for (TrieNode child : children) {
if (Character.isLowerCase(child.value))
child.match(prefix, word + child.value);
}
}
}
void getWords(String word) {
for (TrieNode child : children) {
if (child.isWord) {
System.out.println(word + child.value);
}
child.getWords(word + child.value);
}
}
public static void main(String[] args) {
TrieNode root = new TrieNode('-');
root.insert("HelloMars");
root.insert("HelloWorld");
root.insert("HelloWorldMars");
root.insert("HiHo");
root.match("HH", "");
}
}
- shajibcse067 August 01, 2016