1、题目描述
设计一个数据结构,可以储存单词,查找单词。
找单词的时候“.”表示任意a-z的字母。
2、思路
map<int,vector<string>>,key为字符串的长度,value为加入的长度为key的字符串。
add操作,将字符串插入到对应长度的map中。
search操作,提取出对应长度的字符串数组。
在这个数组中找到有没有匹配的,有true,没有false。
3、代码
class WordDictionary {
public:
/** Initialize your data structure here. */
map<int,vector<string>>s;
WordDictionary() {
}
/** Adds a word into the data structure. */
void addWord(string word) {
int l = word.size();
s[l].push_back(word);
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
bool search(string word) {
//return dfs(word,0);
int l = word.size();
vector<string>v=s[l];
for(int i=0;i<v.size();i++){
if(word==v[i])
return true;
int j=0;
for(;j<l;j++){
if(word[j]!=v[i][j] && word[j]!='.')
break;
}
if(j==l)
return true;
}
return false;
}
};