leetcode 211. Add and Search Word - Data structure design Trie树
生活随笔
收集整理的這篇文章主要介紹了
leetcode 211. Add and Search Word - Data structure design Trie树
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接
寫一個數據結構, 支持兩種操作。 加入一個字符串, 查找一個字符串是否存在。查找的時候, '.'可以代表任意一個字符。
?
顯然是Trie樹, 添加就是正常的添加, 查找的時候只要dfs查找就可以。 具體dfs方法看代碼。
?
struct node {node *next[26];int idEnd;node() {memset(next, NULL, sizeof(next));idEnd = 0;} }; class WordDictionary { public:// Adds a word into the data structure.node *root = new node();void addWord(string word) {node *p = root;int len = word.size();for(int i = 0; i<len; i++) {if(p->next[word[i]-'a'] == NULL)p->next[word[i]-'a'] = new node();p = p->next[word[i]-'a'];}p->idEnd = 1;return ;}int dfs(string word, int pos, node *p) { //pos是代表當前是在哪一位。if(pos == word.size())return p->idEnd;int len = word.size();for(int i = pos; i<len; i++) {if(word[i] == '.') {for(int j = 0; j<26; j++) {if(p->next[j] == NULL)continue;if(dfs(word, pos+1, p->next[j]))return 1;}return 0;} else if(p->next[word[i]-'a'] != NULL) {return dfs(word, pos+1, p->next[word[i]-'a']);} else {return 0;}}}// 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) {return dfs(word, 0, root);} };?
轉載于:https://www.cnblogs.com/yohaha/p/5119997.html
總結
以上是生活随笔為你收集整理的leetcode 211. Add and Search Word - Data structure design Trie树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: phpStorm打开提示 failed
- 下一篇: 测试用例设计步骤