题目描述:
Given many words, words[i] has weight i.
Design a class WordFilter that supports one function, WordFilter.f(String prefix, String suffix). It will return the word with given prefix and suffix with maximum weight. If no word exists, return -1.
Examples:
Input:
WordFilter(["apple"])
WordFilter.f("a", "e") // returns 0
WordFilter.f("b", "") // returns -1
Note:
1. words has length in range [1, 15000].
2. For each test case, up to words.length queries WordFilter.f may be made.
3. words[i] has length in range [1, 10].
4. prefix, suffix have lengths in range [0, 10].
5. words[i] and prefix, suffix queries consist of lowercase letters only.
class TrieNode {
public:
bool isWord;
TrieNode* child[26];
TrieNode()
{
isWord=false;
for(int i=0;i<26;i++) child[i]=NULL;
}
};
class WordFilter {
public:
WordFilter(vector<string> words) {
for(int i=0;i<words.size();i++)
{
insert(words[i]);
weight[words[i]]=i;
}
}
int f(string prefix, string suffix) {
//利用prefix遍历到某一个节点
TrieNode* p=root;
bool flag=true;
vector<string> words;
for(auto c:prefix){
int i=c-'a';
if(p->child[i]==NULL)
{
flag=false;//Trie中不存在给定前缀
break;
}
else p=p->child[i];
}
if(flag) findAllWords(words,p,prefix);
if(words.empty()) return -1;
int n=suffix.size();
int max_weight=-1;
for(auto word:words) //判断前缀匹配的单词中哪些词还匹配后缀
{
if(word.size()<n) continue;
if(word.substr(word.size()-n)==suffix)
max_weight=max(max_weight,weight[word]);
}
return max_weight;
}
void insert(string word) {
TrieNode* p=root;
for(int i=0;i<word.size();i++)
{
if(p->child[word[i]-'a']==NULL)
p->child[word[i]-'a']=new TrieNode();
if(i==word.size()-1) p->child[word[i]-'a']->isWord=true;
p=p->child[word[i]-'a'];
}
}
// 利用prefix遍历到某一个节点,返回该节点之后的所有单词
void findAllWords(vector<string>& words, TrieNode* p, string cur){
if(p->isWord) words.push_back(cur);
for(int i = 0; i < 26; i++){
if(p->child[i]){
cur.push_back(char('a'+i));
findAllWords(words,p->child[i],cur);
cur.pop_back();
}
}
}
private:
TrieNode* root=new TrieNode();
unordered_map<string,int> weight;
};
/**
* Your WordFilter object will be instantiated and called as such:
* WordFilter obj = new WordFilter(words);
* int param_1 = obj.f(prefix,suffix);
*/