trie(前缀树)
目錄
- trie(前綴樹)
- 代碼實現
- 參考資料
trie(前綴樹)
問題描述
給你10000個字符串集,如何快速判斷一個字符串在沒在這字符串集中?
解決思路
- 如果使用最傻的遍歷整個集合,時間復雜度O(n^2),顯然不可行,時間復雜度太大
- 使用trie樹,它的特點是:
- 核心思想:用空間換時間
- 使用字符串的公共前綴,節省查找時間
- 定義一個頭節點,判斷是否有走向某個節點的路,(這塊的路代表的是節點的指向)
構建一棵前綴樹
擴充內容
- 我還想知道有多少字符串是以"be"開始的?
- 某個字符串被加了多少次?
思路:
- 給節點設置個屬性,path 表示經過節點多少次,就可以判斷前綴為"be"的字符串有多少個
- 給節點一個屬性,end 表示這條鏈被加入多少次
代碼實現
package com.sparrow.zg.tree;/*** 前綴樹*/
public class TrieTree {public static class TreeNode {public int path;public int end;public TreeNode[] nexts;public TreeNode() {path = 0;end = 0;nexts = new TreeNode[26];//當前節點只能接受a~b}}/*** 前綴樹:* 1.查n個字符傳中有多少個以**開始的*/public static class Trie {private TreeNode root;public Trie() {root = new TreeNode();}public void insert(String word) {if (word == null) {return;}char[] chs = word.toCharArray();int index = 0;TreeNode node = root;for (int i = 0; i < chs.length; i++) {index = chs[i] - 'a';if (node.nexts[index] == null) {node.nexts[index] = new TreeNode();}node = node.nexts[index];node.path++;}node.end++;}/*** 查找某個字串被添加多少次** @param word 查詢的字串* @return 被添加的次數*/public int search(String word) {if (word == null) {return 0;}char[] chs = word.toCharArray();TreeNode node = root;int index = 0;for (int i = 0; i < chs.length; i++) {index = chs[i] - 'a';if (node.nexts[index] == null) {return 0;}node = node.nexts[index];}return node.end;}/*** 記錄多少字符串是以word開頭的** @param word 前綴字符串* @return 字符串的個數*/public int prefixNumber(String word) {if (word == null) {return 0;}char[] chs = word.toCharArray();int index = 0;TreeNode node = root;for (int i = 0; i < chs.length; i++) {index = chs[i] - 'a';if (node.nexts[index] == null) {return 0;}node = node.nexts[index];}return node.path;}/*** 刪除對應的字符串** @param word 要刪除的字符串*/public void delete(String word) {if (word == null) {return;}if (search(word) == 0) {return;}char[] chs = word.toCharArray();int index;TreeNode node = root;for (int i = 0; i < chs.length; i++) {index = chs[i] - 'a';if (--node.nexts[index].path == 0) {//如果當前節點指向的節點的path==0,說明下面節點只走過一次node.nexts[index] = null;//將下個節點的指向空return;}node = node.nexts[index];}node.end--;}}
參考資料
Trie(前綴樹/字典樹)及其應用
轉載于:https://www.cnblogs.com/sparrowzg/p/10526028.html
總結
- 上一篇: CSS3---6.文字阴影
- 下一篇: CF533A Berland Miner