package trie;public class Trie {private int size = 26; //26个字母private TrieNode root;Trie() {root = new TrieNode(); //树的跟节点}private class TrieNode { //节点类private int num; //通过该节点的字符串的数目private TrieNode[] son; //子节点private boolean isEnd; //判断是否是字符串的最后一个字母private char val; //节点值TrieNode() {num = 1;son = new TrieNode[size];isEnd = false;}}public void insert(String str) { //插入操作if (str == null || str.length() == 0) {return;}TrieNode node = root;char[] chars = str.toCharArray();for (int i = 0; i < chars.length; i++) {int pos = chars[i] – ‘a’; if (node.son[pos] == null) {node.son[pos] = new TrieNode();node.son[pos].val = chars[i];} else {node.son[pos].num++;}node = node.son[pos];}node.isEnd = true;}public int countPrefix(String preStr) { //查找前缀的数目if (preStr == null || preStr.length() == 0) {return -1;}TrieNode node = root;char[] chars = preStr.toCharArray();for (int i = 0; i < chars.length; i++) {int pos = chars[i] – ‘a’;if (node.son[pos] == null) {return 0;} else {node = node.son[pos];}}return node.num;}public boolean isExist(String str) {//判断某个字符串是否已经在书中if (str == null || str.length() == 0) {return false;}TrieNode node = root;char[] chars = str.toCharArray();for (int i = 0; i < chars.length; i++) {int pos = chars[i] – ‘a’;if (node.son[pos] == null) {return false;} else {node = node.son[pos];}}return node.isEnd;}public void preTraverse(TrieNode node) {//前序遍历if (node != null) {System.out.print(node.val);for (TrieNode child : node.son) {preTraverse(child);}}}public void sortStrs(TrieNode node, String str) {//通过前序遍历,按顺序打印字符串if (node != null) {if (node.isEnd == true) {String temp = str + node.val;System.out.println(temp);}for (TrieNode child : node.son) {sortStrs(child, str + node.val);}}}public int countSubStr(String str) {//计算子串出现的次数if (str == null || str.length() == 0) {return 0;}TrieNode node = root;char[] chars = str.toCharArray();for (int i = 0; i < chars.length; i++) {int pos = chars[i] – ‘a’;if (node.son[pos] == null) {return 0;} else {node = node.son[pos];}}return node.num;}public static void main(String[] args) {Trie tree = new Trie();String[] strs = { “banan”, “band”, “absolute”, “acm” };String[] preFix = { “ba”, “band”, “abc” };String test = “abcabcabcassadfsdfsd”;String subStr = “d”;char[] chars = test.toCharArray();for (int i = 0; i < test.length() – 1; i++) {tree.insert(test.substring(i, test.length()));}// for (String str : strs) {// tree.insert(str);// }// tree.preTraverse(tree.root);// tree.sortStrs(tree.root, “”);System.out.println(tree.countSubStr(subStr));}}
trie树,串排序,子串出现次数
原文作者:Trie树
原文地址: https://blog.csdn.net/archeryuan123/article/details/50284273
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://blog.csdn.net/archeryuan123/article/details/50284273
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。