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 -1Note:
wordshas length in range[1, 15000].For each test case, up to
words.lengthqueriesWordFilter.fmay be made.words[i]has length in range[1, 10].prefix, suffixhave lengths in range[0, 10].words[i]andprefix, suffixqueries consist of lowercase letters only.
class WordFilter {
public:
WordFilter(vector<string>& words) { // time: O(N * L^2); space: O(N * L^2)
for (int k = 0; k < words.size(); ++k) {
for (int i = 0; i <= words[k].length(); ++i) {
for (int j = 0; j <= words[k].length(); ++j) {
m[words[k].substr(0, i) + "#" + words[k].substr(words[k].length() - j)] = k;
}
}
}
}
int f(string prefix, string suffix) { // time: O(1)
string key_str = prefix + "#" + suffix;
return m.count(key_str) != 0 ? m[key_str] : -1;
}
private:
unordered_map<string, int> m;
};Last updated
Was this helpful?