标签:
字典树数据结构实现
1 public class Trie { 2 //字典树子节点最多值,任意一个单词都是由,26个字母组成的 3 private int SIZE = 26; 4 //根节点 5 private TrieNode root; 6 //初始化字典树 7 public Trie() { 8 root = new TrieNode(); 9 } 10 11 //字典树节点 12 private class TrieNode{ 13 //存放子节点的数组 14 private TrieNode[] sonNode; 15 //是否是最后一个节点 16 private boolean isEnd; 17 //节点的值 18 private char val; 19 //有多少个单词通过这个节点,即节点字符出现的次数 20 private int num; 21 TrieNode(){ 22 num = 1; 23 sonNode = new TrieNode[SIZE]; 24 isEnd = false; 25 } 26 } 27 28 //方法,建立字典树,在字典树中插入一个单词 29 public void insert(String str){ 30 if(str == null || str.length() == 0){ 31 return ; 32 } 33 34 //获得字典树 35 TrieNode node = root; 36 //把字符串转换成字符数组 37 char[] letters = str.toCharArray(); 38 //遍历字符数组,将其插入字典树中 39 for(int i=0; i < letters.length ; i++){ 40 int pos = letters[i] - ‘a‘; 41 if(node.sonNode[pos] == null){ 42 node.sonNode[pos] = new TrieNode(); 43 node.sonNode[pos].val = letters[i]; 44 }else{ 45 node.sonNode[pos].num++; 46 } 47 node = node.sonNode[pos]; 48 } 49 node.isEnd = true; 50 } 51 52 //计算单词前缀的数量 53 public int countPrefix(String prefix){ 54 if(prefix == null || prefix.length() == 0){ 55 return -1; 56 } 57 //得到字典树 58 TrieNode node = root; 59 char[] letters = prefix.toCharArray(); 60 for(int i = 0 , len = letters.length; i < len; i++){ 61 int pos = letters[i] - ‘a‘; 62 if(node.sonNode[pos] == null){ 63 return 0; 64 }else{ 65 node = node.sonNode[pos]; 66 } 67 } 68 return node.num; 69 } 70 71 //在字典树中查找一个完全匹配的单词 72 public boolean has(String str){ 73 if(str == null || str.length() == 0){ 74 return false; 75 } 76 //得到字典树 77 TrieNode node = root; 78 char[] letters = str.toCharArray(); 79 for(int i = 0, len = str.length(); i < len; i++){ 80 int pos = letters[i] - ‘a‘; 81 if(node.sonNode[pos] !=null){ 82 node = node.sonNode[pos]; 83 }else{ 84 return false; 85 } 86 } 87 return node.isEnd; 88 } 89 90 //前序遍历字典树 91 public void preTraverse(TrieNode node){ 92 if(node != null){ 93 System.out.print(node.val + "-"); 94 for(TrieNode child : node.sonNode){ 95 preTraverse(child); 96 } 97 } 98 } 99 100 //获取根节点 101 public TrieNode getRoot(){ 102 return this.root; 103 } 104 105 //测试 106 public static void main(String[] args) { 107 //构造字典树 108 Trie tree = new Trie(); 109 String[] strs = {"banana","band","bee","absolute","acm"}; 110 String[] prefix = {"ba","b","band","abc"}; 111 for(String string : strs){ 112 tree.insert(string); 113 } 114 115 System.out.println("prefix :" + tree.has("abc")); 116 System.out.println("prefix :" + tree.has("band")); 117 System.out.println("-------------"); 118 tree.preTraverse(tree.getRoot()); 119 System.out.println("\n-------------"); 120 for(String pre: prefix){ 121 int num = tree.countPrefix(pre); 122 System.out.println(pre + " -> " + num); 123 } 124 125 } 126 127 }
标签:
原文地址:http://www.cnblogs.com/lsf2015/p/4668244.html