请你设计一个数据结构,支持 添加新单词 和 查找字符串是否与任何先前添加的字符串匹配 。
实现词典类 WordDictionary :
WordDictionary() 初始化词典对象
void addWord(word) 将 word 添加到数据结构中,之后可以对它进行匹配
bool search(word) 如果数据结构中存在字符串与 word 匹配,则返回 true ;否则,返回 false 。word 中可能包含一些 '.' ,每个 . 都可以表示任何一个字母。
示例:
输入:
["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
输出:
[null,null,null,null,false,true,true,true]
解释:
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("bad");
wordDictionary.addWord("dad");
wordDictionary.addWord("mad");
wordDictionary.search("pad"); // return False
wordDictionary.search("bad"); // return True
wordDictionary.search(".ad"); // return True
wordDictionary.search("b.."); // return True
解题思路:
查询单词的时候,虽然有".",但是单词的长度是不变的,所以可以以单词长度作为map的key。
class WordDictionary { Map<Integer, List<String>> map; public WordDictionary() { map = new HashMap<>(); } public void addWord(String word) { if(!map.containsKey(word.length())) { map.put(word.length(), new ArrayList<>()); } map.get(word.length()).add(word); } public boolean search(String word) { if(!map.containsKey(word.length())) { return false; } for(String dictWord: map.get(word.length())) { int i = 0; for(; i < word.length(); i++) { if(word.charAt(i) == '.'){ continue; } if(word.charAt(i) != dictWord.charAt(i)) { break; } } if(i == word.length()) { return true; } } return false; } } /** * Your WordDictionary object will be instantiated and called as such: * WordDictionary obj = new WordDictionary(); * obj.addWord(word); * boolean param_2 = obj.search(word); */