2018年7月29日 星期日

[LeetCode] 211. Add and Search Word - Data structure design

轉自LeetCode

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.
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.
<Solution>

這題可以看成是 208. Implement Trie (Prefix Tree) 的衍生題

主要想法差不多,唯一比較不一樣的地方是,這次搜尋的可以用萬用字元 .

想法如下
  • 如果沒遇到萬用字元,那麼就是正常歷遍 Prefix Tree 來找
  • 如果遇到萬用字元,那麼歷遍當下 node 所有可連接的節點,並配合 dfs 的方式來找
code 如下

Java

class WordDictionary {
private TrieNode mRoot;
/** Initialize your data structure here. */
public WordDictionary() {
mRoot = new TrieNode();
}
/** Adds a word into the data structure. */
public void addWord(String word) {
TrieNode node = mRoot;
for(final char c : word.toCharArray()) {
if(!node.containsKey(c)) {
node.put(c, new TrieNode());
}
node = node.get(c);
}
node.setEnd();
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
public boolean search(String word) {
return dfs(mRoot, word);
}
private boolean dfs(final TrieNode startNode, final String word) {
final int len = word.length();
TrieNode node = startNode;
char c;
for(int i = 0; i < len; i++) {
c = word.charAt(i);
if(c != '.' && node != null) {
node = node.get(c);
}
else if(c == '.' && node != null) {
for(int j = 0; j < 26; j++) {
if(dfs(node.get((char)('a' + j)), word.substring(i+1))) {
return true;
}
}
return false;
}
else {
break;
}
}
return node != null && node.isEnd();
}
}
class TrieNode {
private static final int LEN = 26;
private TrieNode[] mList;
private boolean mIsEnd;
public TrieNode() {
mList = new TrieNode[26];
mIsEnd = false;
}
public void setEnd() {
mIsEnd = true;
}
public boolean isEnd() {
return mIsEnd;
}
public void put(final char key, final TrieNode node) {
mList[key - 'a'] = node;
}
public TrieNode get(final char key) {
return mList[key - 'a'];
}
public boolean containsKey(final char key) {
return mList[key - 'a'] != null;
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/

沒有留言:

張貼留言