日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

trie(前缀树)

發布時間:2023/11/27 生活经验 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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

總結

以上是生活随笔為你收集整理的trie(前缀树)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。