目录
- 目录
- 思路
- 思路
- AC代码
思路
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
思路
因为之前做了一道字典树的题目,这道题目需要借鉴字典树的数据结构。点击进入字典树参考链接。
具体思路如下:
- 用Trie树来存储插入的字符串。
- 用DFS来搜索Trie树中的字符串。
为什么这里只能用DFS而不能用BFS呢?
是因为:BFS无法保证下一层查找的结点是否属于当前的父节点。
AC代码
有了字典树的基础,我直接上AC代码了,大家可以通过代码学习具体的思路:
import java.util.HashMap;
class WordTrieNode {
boolean isWord;
int index;
HashMap<Character, WordTrieNode> nexts;
public WordTrieNode() {
nexts = new HashMap<Character, WordTrieNode>();
}
}
public class WordDictionary {
private WordTrieNode root;
public WordDictionary() {
root = new WordTrieNode();
}
// Adds a word into the data structure.
public void addWord(String word) {
WordTrieNode p = root;
int i = 0, len = word.length();
// traverse existing
while (i < len) {
char ch = word.charAt(i);
if (p.nexts.containsKey(ch)) {
p = p.nexts.get(ch);
i ++;
} else {
break;
}
}
// append new word
while (i < len) {
WordTrieNode newNode = new WordTrieNode();
newNode.index = i;
p.nexts.put(word.charAt(i), newNode);
p = newNode;
i ++;
}
// set word end
p.isWord = true;
}
// 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) {
if (word == null || word.length() == 0) {
return false;
}
WordTrieNode p = root;
return dfs(word, 0, p);
}
private boolean dfs(String word, int index, WordTrieNode p) {
if (index == word.length() - 1) {
if (word.charAt(index) == ‘.‘) {
for (WordTrieNode node : p.nexts.values()) {
if (node.isWord) {
return true;
}
}
return false;
} else {
WordTrieNode endNode = p.nexts.get(word.charAt(index));
return endNode != null && endNode.isWord;
}
}
if (index >= word.length()) {
return false;
}
if (word.charAt(index) == ‘.‘) {
boolean res = false;
for (WordTrieNode node : p.nexts.values()) {
res |= dfs(word, index + 1, node);
}
return res;
} else {
if (p.nexts.containsKey(word.charAt(index))) {
return dfs(word, index + 1, p.nexts.get(word.charAt(index)));
} else {
return false;
}
}
}
}
// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");
时间: 2024-10-07 18:07:09