package example.test.google;
import java.util.HashMap;
import java.util.Map;
public class TFK {
public static void main(String[] args) {
TFK test = new TFK();
test.test();
}
public void test() {
String sentence = "this is a test";
Path path = Path.sentenceToPath(sentence);
Node root = new Node();
NodeOperate.addNode(root, path);
sentence = "this is another test";
path = Path.sentenceToPath(sentence);
NodeOperate.addNode(root, path);
}
}
class Node {
String key;
Node value;
Map<String, Node> pair;
}
class NodeOperate {
public static void addNode(Node node, Path path) {
if (node == null || path == null) {
return;
}
if (contains(node, path)) {
Node next = findNode(node, path);
if (next != null) {
updateNode(node);
addNode(next, path.next);
}
} else {
Node next = new Node();
saveNode(node, path, next);
addNode(next, path.next);
}
}
public static void addNode0(Node node, Path path) {
if (node == null || path == null) {
return;
}
if (contains(node, path)) {
Node next = findNode(node, path);
addNode(next, path.next);
} else {
Node next = new Node();
if (node.key != null) {
updateNode(node);
}
saveNode(node, path, next);
addNode(next, path.next);
}
}
public static Node findNode(Node node, Path path) {
if (node.key != null) {
if (node.key.equals(path.word)) {
return node.value;
}
}
return node.pair.get(path.word);
}
public static void saveNode(Node node, Path path, Node next) {
if (node.pair != null) {
node.pair.put(path.word, next);
} else {
node.key = path.word;
node.value = next;
}
}
public static void updateNode(Node node) {
if (node.pair == null) {
node.pair = new HashMap<>();
}
node.pair.put(node.key, node.value);
node.key = null;
node.value = null;
}
public static boolean contains(Node node, Path path) {
if (node.pair != null) {
return node.pair.containsKey(path.word);
}
if (node.key != null) {
return node.key.equals(path.word);
}
return false;
}
}