链接:. - 力扣(LeetCode)
题解:
class Solution {
private:struct Trie {Trie() {end = false;index = -1;next.resize(26);}bool end;int index;std::vector<std::unique_ptr<Trie>> next;};void insert_trie(int index, Trie* root, std::string& word) {Trie* cur = root;for (int i = 0; i < word.size(); ++i) {int index = word[i] - 'a';if (!cur->next[index]) {std:unique_ptr<Trie> tmp = make_unique<Trie>();cur->next[index].reset(tmp.release());}cur = cur->next[index].get();}cur->index = index;}
public:vector<vector<int>> multiSearch(string big, vector<string>& smalls) {if (smalls.size() <= 0) {return {};}std::vector<std::vector<int>> result(smalls.size(), std::vector<int>{});std::unique_ptr<Trie> root = make_unique<Trie>();for (int i = 0; i < smalls.size(); ++i) {// 插入small,且记录当前small的index iinsert_trie(i, root.get(), smalls[i]);}// 从每一个位置,遍历bigfor (int i = 0; i < big.size(); ++i) {Trie* cur = root.get();// 判断后面的字符,是否存在匹配过的for (int j = i; j < big.size(); ++j) {int index = big[j] - 'a';// 不匹配的停止if (!cur->next[index]) {break;}cur = cur->next[index].get();// 如果存在末尾if (cur->index != -1) {// 更新结果集合result[cur->index].push_back(i);}}}return result;}
};