Created
March 11, 2014 13:15
-
-
Save NotBadPad/9485362 to your computer and use it in GitHub Desktop.
标准的trie查找树,可以高效的进行英文单词匹配
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.gj.trie; | |
/** | |
* 标准trie查找树,该实现仅能进行英文单词查找 | |
* @author guojing | |
* | |
* 2013-8-1 | |
*/ | |
public class StandardTrie { | |
enum NodeKind{LN,BN}; | |
class TrieNode{ | |
char key; | |
TrieNode[] points=null; | |
NodeKind kind=null; | |
} | |
class LeafNode extends TrieNode{ | |
public LeafNode(char k) { | |
super.key=k; | |
super.kind=NodeKind.LN; | |
} | |
} | |
class BranchNode extends TrieNode{ | |
public BranchNode(char k){ | |
super.key=k; | |
super.kind=NodeKind.BN; | |
super.points=new TrieNode[27]; | |
} | |
} | |
//根节点 | |
private TrieNode root=new BranchNode(' '); | |
public void insert(String word){ | |
TrieNode curNode=root; | |
word=word+"$"; | |
char[] chars=word.toCharArray(); | |
for(int i=0;i<chars.length;i++){ | |
if('$'==chars[i]){ | |
curNode.points[26]=new LeafNode('$'); | |
} | |
else{ | |
int position=chars[i]-'a'; | |
if(null==curNode.points[position]){ | |
curNode.points[position]=new BranchNode(chars[i]); | |
} | |
curNode=curNode.points[position]; | |
} | |
} | |
} | |
public boolean fullMatch(String word){ | |
TrieNode curNode=root; | |
char[] chars=word.toCharArray(); | |
for(int i=0;i<chars.length;i++){ | |
int position=chars[i]-'a'; | |
if(null==curNode.points[position]){ | |
return false; | |
} | |
else{ | |
curNode=curNode.points[position]; | |
System.out.print(curNode.key + " -> "); | |
} | |
} | |
if(null!=curNode.points[26]){ | |
System.out.println("$"); | |
return true; | |
}else{ | |
return false; | |
} | |
} | |
public void preRootTraverse(TrieNode curNode){ | |
if(null!=curNode){ | |
System.out.print(curNode.key+" "); | |
if(curNode.kind==NodeKind.BN){ | |
for(TrieNode childNode:curNode.points){ | |
preRootTraverse(childNode); | |
} | |
} | |
} | |
} | |
public TrieNode getRoot(){ | |
return root; | |
} | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
StandardTrie sdTrie=new StandardTrie(); | |
sdTrie.insert("position"); | |
sdTrie.insert("bird"); | |
sdTrie.insert("current"); | |
sdTrie.insert("book"); | |
sdTrie.insert("bool"); | |
sdTrie.insert("bell"); | |
if(sdTrie.fullMatch("book")){ | |
System.out.println("查找到了!"); | |
}else{ | |
System.out.println("未找到!"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment