745. Prefix and Suffix Search
问题描述:
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:
words
has length in range[1, 15000]
.- For each test case, up to
words.length
queriesWordFilter.f
may be made. words[i]
has length in range[1, 10]
.prefix, suffix
have lengths in range[0, 10]
.words[i]
andprefix, suffix
queries consist of lowercase letters only.
解题思路:
看到根据前缀找相应的字符串,首先想到了trie树。
由于要返回最大的权重的字符串,我们可以用一个map来存储字符串和相应的权重。
这里要实现的方法是:根据前缀返回包含此前缀的所有的字符串, 可以用DFS来进行寻找。
对包含次前缀的字符串,我们再对其后缀进行查验,并且检查其对应权重,要返回权重最大的字符串
代码:
class TrieNode { public: TrieNode* child[26]; bool isWord; TrieNode(): isWord(false){ for(auto &a : child){ a = NULL; } } }; class WordFilter { public: WordFilter(vector<string> words) { root = new TrieNode(); int i = 0; for(auto w : words){ insert(w); weight_map[w] = i++; } } int f(string prefix, string suffix) { vector<string> pre = findAllPrefix(prefix); if(pre.empty()) return -1; int weight = -1; for(auto w : pre){ if(isSufix(w, suffix) && weight_map[w] > weight){ weight = weight_map[w]; } } return weight; } private: unordered_map<string, int> weight_map; TrieNode* root; void insert(string word){ TrieNode* p = root; for(auto c : word){ int i = c - 'a'; if(!p->child[i]){ p->child[i] = new TrieNode(); } p = p->child[i]; } p->isWord = true; } bool isSufix(string w, string suf){ int m = w.size()-1; int n = suf.size()-1; if(m < n) return false; while(n > -1){ if(suf[n--] != w[m--]) return false; } return true; } void findAllWords(vector<string> &allW, TrieNode* p, string cur){ if(p->isWord) allW.push_back(cur); for(int i = 0; i < 26; i++){ if(p->child[i]){ cur.push_back(char('a'+i)); findAllWords(allW, p->child[i], cur); cur.pop_back(); } } } vector<string> findAllPrefix(string pre){ TrieNode* p = root; vector<string> ret; for(auto c : pre){ int i = c - 'a'; if(!p->child[i]) return ret; p = p->child[i]; } findAllWords(ret, p, pre); return ret; } }; /** * Your WordFilter object will be instantiated and called as such: * WordFilter obj = new WordFilter(words); * int param_1 = obj.f(prefix,suffix); */