211. 添加与搜索单词 - 数据结构设计
生活随笔
收集整理的這篇文章主要介紹了
211. 添加与搜索单词 - 数据结构设计
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
211. 添加與搜索單詞 - 數據結構設計
請你設計一個數據結構,支持 添加新單詞 和 查找字符串是否與任何先前添加的字符串匹配 。
實現詞典類 WordDictionary :
WordDictionary() 初始化詞典對象
void addWord(word) 將 word 添加到數據結構中,之后可以對它進行匹配
bool search(word) 如果數據結構中存在字符串與 word 匹配,則返回 true ;否則,返回 false 。word 中可能包含一些 ‘.’ ,每個 . 都可以表示任何一個字母。
提示:
- 1 <= word.length <= 500
- addWord 中的 word 由小寫英文字母組成
- search 中的 word 由 ‘.’ 或小寫英文字母組成
- 最多調用 50000 次 addWord 和 search
解題思路
使用字典樹存儲添加進來的字符串,搜索字符串時,如果遇到’.’,因為每個 . 都可以表示任何一個字母,那么就可以當成遍歷當前下標所有可能的字母,對于每種字母的選擇情況繼續向下遞歸。
代碼
class WordDictionary {Node root = new Node();public WordDictionary() {}public boolean Search(String s, int idx, Node cur) {if (idx == s.length()) {return cur.isEnd;}if (s.charAt(idx) == '.') {boolean res = false;for (int i = 0; i < 26; i++) {if (cur.nodes[i] != null)res |= Search(s, idx + 1, cur.nodes[i]);}return res;} else {if (cur.nodes[s.charAt(idx) - 'a'] == null)return false;return Search(s, idx + 1, cur.nodes[s.charAt(idx) - 'a']);}}public void addWord(String s) {int n = s.length();Node cur = root;for (int i = 0; i < n; i++) {if (cur.nodes[s.charAt(i) - 'a'] == null)cur.nodes[s.charAt(i) - 'a'] = new Node();cur = cur.nodes[s.charAt(i) - 'a'];}cur.isEnd = true;}public boolean search(String word) {return Search(word,0,root);}}class Node {boolean isEnd;Node[] nodes;public Node() {nodes = new Node[26];}} /*** Your WordDictionary object will be instantiated and called as such:* WordDictionary obj = new WordDictionary();* obj.addWord(word);* boolean param_2 = obj.search(word);*/總結
以上是生活随笔為你收集整理的211. 添加与搜索单词 - 数据结构设计的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 做梦梦到涂指甲油是什么意思
- 下一篇: 2044. 统计按位或能得到最大值的子集