예제 #1
0
  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;*/
  }
예제 #2
0
  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);
  }
예제 #3
0
  public TrieNode getNode(char c) {
    TrieNode nodeToCheck = new TrieNode(c);
    for (TrieNode node : nodes) {
      if (node.equals(nodeToCheck)) return node;
    }

    return null;
  }
예제 #4
0
 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());
     }
   }
 }
예제 #5
0
  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;
  }