脚本宝典收集整理的这篇文章主要介绍了[LintCode/LeetCode] Add and Search Word,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
Problem
Design a data structure that supports the following two operations: addWord(word) and 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
public class WordDictionary {
class TrieNode {
char val;
boolean isWord;
TrieNode[] children;
TrieNode() {
children = new TrieNode[26];
}
TrieNode(char ch) {
children = new TrieNode[26];
val = ch;
}
}
TrieNode root = new TrieNode();
// Adds a word into the data structure.
public void addWord(String word) {
TrieNode node = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (node.children[ch-'a'] == null) node.children[ch-'a'] = new TrieNode(ch);
node = node.children[ch-'a'];
}
node.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) {
return helper(word, 0, root);
}
public boolean helper(String word, int pos, TrieNode node) {
if (pos == word.length()) return node.isWord;
char ch = word.charAt(pos);
if (ch != '.') return node.children[ch-'a'] != null && helper(word, pos+1, node.children[ch-'a']);
else {
for (int i = 0; i < 26; i++) {
if (node.children[i] != null && helper(word, pos+1, node.children[i])) return true;
}
return false;
}
}
}
以上是脚本宝典为你收集整理的[LintCode/LeetCode] Add and Search Word全部内容,希望文章能够帮你解决[LintCode/LeetCode] Add and Search Word所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。