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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode 211. 添加与搜索单词 - 数据结构设计(Trie树)

發布時間:2024/7/5 编程问答 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode 211. 添加与搜索单词 - 数据结构设计(Trie树) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1. 題目

設計一個支持以下兩種操作的數據結構:

void addWord(word)
bool search(word)
search(word) 可以搜索文字或正則表達式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一個字母。

示例: addWord("bad") addWord("dad") addWord("mad") search("pad") -> false search("bad") -> true search(".ad") -> true search("b..") -> true 說明: 你可以假設所有單詞都是由小寫字母 a-z 組成的。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/add-and-search-word-data-structure-design
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。

2. Trie解題

  • 構建Trie樹
  • 回溯查找,遇見.在所有的子樹里查找,沒有遇見.在,當前相等的情況下,再繼續在所有的子樹中遞歸查找
class TrieNode { public:char ch;TrieNode *next[26];bool isEnd;TrieNode(char c = '/'):ch(c),isEnd(false) {memset(next, 0, sizeof(TrieNode*)*26);} }; class Trie { public:TrieNode *root;Trie(){root = new TrieNode();}~Trie(){destroy(root);}void destroy(TrieNode *root){if(root == NULL)return;for(int i = 0; i < 26; i++)destroy(root->next[i]);delete root;}void insert(string str){TrieNode *cur = root;for(char s:str){if(cur->next[s-'a'] == NULL)cur->next[s-'a'] = new TrieNode(s);cur = cur->next[s-'a'];}cur->isEnd = true;} }; class WordDictionary {Trie tree; public:/** Initialize your data structure here. */WordDictionary() {}/** Adds a word into the data structure. */void addWord(string word) {tree.insert(word);}/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */bool search(string word) {TrieNode *cur = tree.root;bool found = false;for(int i = 0; i < 26; ++i){find(word,cur->next[i],0,found);}return found;}void find(string &word, TrieNode *root, int idx, bool &found){if(found || !root)return;if(idx == word.size()-1){if(root->isEnd)if(word[idx] == '.' || word[idx] == root->ch)found = true;return;}if((word[idx] != '.'&&root->ch == word[idx])|| word[idx] == '.'){ for(int i = 0; i < 26; ++i){find(word,root->next[i],idx+1,found);}}} };

總結

以上是生活随笔為你收集整理的LeetCode 211. 添加与搜索单词 - 数据结构设计(Trie树)的全部內容,希望文章能夠幫你解決所遇到的問題。

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