public int countBeginning(String word) { TrieNode trie = rootNode; int count = 0; for (char c : word.toCharArray()) { trie = trie.getNode(c); if (trie == null) return 0; } return trie.size; /*Queue<TrieNode> trieNodes = new ArrayDeque<>(); trieNodes.add(trie); while (!trieNodes.isEmpty()) { TrieNode trieNode = trieNodes.poll(); for (TrieNode node : trieNode.getNodes()) { if (node.equals((char) 0)) count++; else trieNodes.add(node); } } return count;*/ }
public void addWord(String word) { TrieNode trie = rootNode; int count = 0; StringBuilder stringBuffer = new StringBuilder(); // TrieNodeLookup quickLookup = getQuickLookup(word); // System.out.println("quickLookup.startIndex = " + quickLookup.startIndex + " " + // quickLookup.trieNode.toString()); // TrieNode trie = quickLookup.trieNode; // stringBuffer.append(word.substring(0, quickLookup.startIndex)); // System.out.println("trie = " + trie + " " + stringBuffer); // if (word.length() > quickLookup.startIndex) { // word = word.substring(quickLookup.startIndex); for (char c : word.toCharArray()) { stringBuffer.append(c); count++; TrieNode trieN = trie.getNode(c); if (trieN == null) { trieN = new TrieNode(c); trie.addNode(trieN); } trieN.size++; trie = trieN; if (count % 3 == 0) { this.quickLookup.put(stringBuffer.toString(), trie); // System.out.println(this.quickLookup); } } // } TrieNode node = new TrieNode((char) 0); node.size++; trie.addNode(node); }
public TrieNode getNode(char c) { TrieNode nodeToCheck = new TrieNode(c); for (TrieNode node : nodes) { if (node.equals(nodeToCheck)) return node; } return null; }
public void printTrie(TrieNode rootNode, String path) { if (path == null) path = ""; TrieNode endNode = new TrieNode((char) 0); for (TrieNode node : rootNode.getNodes()) { if (node.equals(endNode)) System.out.println(path); else { printTrie(node, path + node.getValue()); } } }
public boolean containsWord(String word) { // TrieNode trie = rootNode; TrieNodeLookup quickLookup = getQuickLookup(word); TrieNode trie = quickLookup.trieNode; if (word.length() < quickLookup.startIndex) { word = word.substring(quickLookup.startIndex); for (char c : word.toCharArray()) { trie = trie.getNode(c); if (trie == null) return false; } } trie = trie.getNode((char) 0); return trie != null; }