211 Design Add and Search Words Data Structure
Design a data structure that supports adding new words and finding if a string matches any previously added string.
Implement the WordDictionary class:
WordDictionary() Initializes the object.
void addWord(word) Adds word to the data structure, it can be matched later.
bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter.
Example:
Input
["WordDictionary","addWord","addWord","addWord","search","search","search","search"][],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
Output
[null,null,null,null,false,true,true,true]
如果长度不同肯定不同。按长度给词典分类。把单词放到相应长度的 set 里面。查找的时候根据长度找到 set ,尝试从 set 里面找,如果找不到,使用 isSame 方法查找是否有含有 .
的匹配结果。
Runtime: 33 ms, faster than 99.89% of Java online submissions for Design Add and Search Words Data Structure.
Memory Usage: 53 MB, less than 50.29% of Java online submissions for Design Add and Search Words Data Structure.
跑出来的结果挺不错,不知道有没有更好的解法。
class WordDictionary {
HashMap<Integer, HashSet<String>> map=new HashMap<>();
public WordDictionary() {
}
public void addWord(String word) {
int len=word.length();
if(!map.containsKey(len)){
HashSet<String> set=new HashSet<>();
set.add(word);
map.put(len,set);
} else {
map.get(len).add(word);
}
}
public boolean search(String word) {
int len=word.length();
HashSet<String> set=map.get(len);
if(set==null) return false;
if(set.contains(word)) return true;
for(String s:set){
if(isSame(s, word)) return true;
}
return false;
}
private boolean isSame(String s1, String s2){
for(int i=0;i<s1.length();++i){
if(s1.charAt(i)!=s2.charAt(i) && s2.charAt(i)!='.') return false;
}
return true;
}
}