題目地址:
https://www.lintcode.com/problem/add-and-search-word-data-structure-design/description
要求實現一個數據結構,可以實現如下操作:
1、添加一個字符串,只含英文小寫字母;
2、給定一個字符串,裏面含英文小寫字母和,視爲通配符。要求在這個數據結構中查找該字符串是否存在。
思路是Trie + DFS。在查找的時候在Trie上用深搜即可,和普通DFS沒有區別。代碼如下:
public class WordDictionary {
class Node {
boolean isWord;
Node[] nexts;
Node() {
nexts = new Node[26];
}
}
private Node root = new Node();
/*
* @param word: Adds a word into the data structure.
* @return: nothing
*/
public void addWord(String word) {
// write your code here
Node cur = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (cur.nexts[c - 'a'] == null) {
cur.nexts[c - 'a'] = new Node();
}
cur = cur.nexts[c - 'a'];
}
cur.isWord = true;
}
/*
* @param word: A word could contain the dot character '.' to represent any one letter.
* @return: if the word is in the data structure.
*/
public boolean search(String word) {
// write your code here
return dfs(root, word, 0);
}
// 在cur爲根的子樹中找word[start: ]是否存在
private boolean dfs(Node cur, String word, int start) {
// 如果已經搜到了末尾,則看一下當前node是否標記了單詞結尾
if (start == word.length()) {
return cur.isWord;
}
char c = word.charAt(start);
if (c != '.') {
if (cur.nexts[c - 'a'] == null) {
return false;
} else {
return dfs(cur.nexts[c - 'a'], word, start + 1);
}
} else {
for (int i = 0; i < cur.nexts.length; i++) {
if (cur.nexts[i] != null && dfs(cur.nexts[i], word, start + 1)) {
return true;
}
}
return false;
}
}
}
時空複雜度,爲Trie節點個數。