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

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

程序员面试金典 - 面试题 17.17. 多次搜索(Trie树)

發(fā)布時(shí)間:2024/7/5 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 程序员面试金典 - 面试题 17.17. 多次搜索(Trie树) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

文章目錄

    • 1. 題目
    • 2. 解題
      • 2.1 暴力超時(shí)
      • 2.2 Trie樹

1. 題目

給定一個(gè)較長字符串big和一個(gè)包含較短字符串的數(shù)組smalls,設(shè)計(jì)一個(gè)方法,根據(jù)smalls中的每一個(gè)較短字符串,對(duì)big進(jìn)行搜索。
輸出smalls中的字符串在big里出現(xiàn)的所有位置positions,其中 positions[i] 為 smalls[i] 出現(xiàn)的所有位置。

示例: 輸入: big = "mississippi" smalls = ["is","ppi","hi","sis","i","ssippi"] 輸出: [[1,4],[8],[],[3],[1,4,7,10],[5]]提示: 0 <= len(big) <= 1000 0 <= len(smalls[i]) <= 1000 smalls的總字符數(shù)不會(huì)超過 100000。 你可以認(rèn)為smalls中沒有重復(fù)字符串。 所有出現(xiàn)的字符均為英文小寫字母。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/multi-search-lcci
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。

2. 解題

2.1 暴力超時(shí)

超時(shí)例子

class Solution { public:vector<vector<int>> multiSearch(string big, vector<string>& smalls) {unordered_map<char,vector<int>> m;int i, j, n = smalls.size();bool found;vector<vector<int>> ans(n);for(i = 0; i < big.size(); ++i)m[big[i]].push_back(i);//每個(gè)字符開始的位置for(i = 0; i < n; ++i){if(smalls[i].empty())continue;for(auto idx : m[smalls[i][0]])//每個(gè)small單詞開始的字符在big里的位置{found = true;if(big.size()-idx < smalls[i].size())break;for(j = 0; j < smalls[i].size(); ++j){ //對(duì)big中每個(gè)開始的位置開始向后查找smallif(big[idx+j] != smalls[i][j]){found = false;break;}}if(found)ans[i].push_back(idx);}}return ans;} };

2.2 Trie樹

  • 將 small 全部插入 trie 樹
  • 遍歷 big 的每個(gè)位置,并從 big 該位置開始在 trie 中查找
class trie { public:bool isEnd = false;trie* next[26] = {NULL};void insert(string& s){trie *cur = this;for(int i = 0; i < s.size(); ++i){if(!cur->next[s[i]-'a'])cur->next[s[i]-'a'] = new trie();cur = cur->next[s[i]-'a'];}cur->isEnd = true;} }; class Solution { public:vector<vector<int>> multiSearch(string big, vector<string>& smalls) {trie* t = new trie();unordered_map<string,int> m;int i, j, n = smalls.size();bool found;vector<vector<int>> ans(n);for(i = 0; i < n; ++i)m[smalls[i]] = i;for(i = 0; i < n; ++i)t->insert(smalls[i]);string s;trie* cur;for(i = 0; i < big.size(); ++i){s = "";cur = t;for(j = i; j < big.size(); ++j){if(!cur->next[big[j]-'a'])break;s += big[j];cur = cur->next[big[j]-'a'];if(cur->isEnd)ans[m[s]].push_back(i);}}return ans;} };

336 ms 108.7 MB

總結(jié)

以上是生活随笔為你收集整理的程序员面试金典 - 面试题 17.17. 多次搜索(Trie树)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。