1. 程式人生 > >leetcode 211. Add and Search Word - Data structure design

leetcode 211. Add and Search Word - Data structure design

cti rsquo .com dict esc sum color pos nsis

Design a data structure that supports the following two operations:

void addWord(word)
bool search(word)

search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.

For example:

addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true

Note:
You may assume that all words are consist of lowercase letters a-z.

click to show hint.

You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.

字典樹+dfs時間復雜度 查詢的時候復雜度O(26^n) n為‘.’的個數

class WordDictionary {
public
: /** Initialize your data structure here. */ WordDictionary() { } class node { public: node* next[26]; int end; node() { for (int i = 0; i < 26; ++i) { next[i] = nullptr; } end = 0
; } }; class Trie { public: node* root; Trie() { root = new node(); } void add(string s) { if (s.size() == 0) return ; node* p = root; for (int i = 0; i < s.size(); ++i) { int x = s[i] - a; if (p->next[x] == nullptr) { p->next[x] = new node(); p = p->next[x]; } else { p = p->next[x]; } } p->end = 1; } bool search(string& s, int pos, node *p) { if (s.size() == pos && p->end == 1) { return true; } if (s[pos] == .) { for (int j = 0; j < 26; ++j) { if (p->next[j] != nullptr) { if (search(s, pos + 1, p->next[j])) return true; } } } else { int x = (int)(s[pos] - a); if (x >= 0 && x < 26 && p->next[x] != nullptr && search(s, pos + 1, p->next[x])) return true; } return false; } }; /** Adds a word into the data structure. */ void addWord(string word) { ac.add(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) { if (ac.search(word, 0, ac.root)) return true; return false; } private: Trie ac; }; /** * Your WordDictionary object will be instantiated and called as such: * WordDictionary obj = new WordDictionary(); * obj.addWord(word); * bool param_2 = obj.search(word); */

leetcode 211. Add and Search Word - Data structure design