【重要】LeetCode 745. 前缀和后缀搜索
题目链接
注意事项
预先计算出每个单词的前缀后缀组合可能性,用特殊符号连接,作为键,对应的最大下标作为值保存入哈希表。检索时,同样用特殊符号连接前后缀,在哈希表中进行搜索。
代码
#include <bits/stdc++.h>
using namespace std;
class WordFilter {
private:
unordered_map<string, int> dict;
public:
WordFilter(vector<string>& words) {
for (int i = 0; i < words.size(); i++) {
int m = words[i].size();
string word = words[i];
for (int prefixLength = 1; prefixLength <= m; prefixLength++) {
for (int suffixLength = 1; suffixLength <= m; suffixLength++) {
string key = word.substr(0, prefixLength) + '#' + word.substr(m - suffixLength);
dict[key] = i;
}
}
}
}
int f(string pref, string suff) {
string target = pref + '#' + suff;
return dict.count(target) ? dict[target] : -1;
}
};