diff --git a/cpp/2206/220619.cpp b/cpp/2206/220619.cpp new file mode 100644 index 0000000..0687c1f --- /dev/null +++ b/cpp/2206/220619.cpp @@ -0,0 +1,83 @@ +#include +#include +#include +#include + +/** + * 1268. Search Suggestions System + * You are given an array of strings products and a string searchWord. + * Design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products. + * Return a list of lists of the suggested products after each character of searchWord is typed. + */ + +class Solution { +private: + int nodes[20008][26]{}; + std::bitset<20008> terminate; + int cnt = 1; + + static constexpr inline int id(char c) { return c - 'a'; } + + void insert(const std::string& s) { + int u = 0; + for (char ch : s) { + int c = id(ch); + if (!nodes[u][c]) + nodes[u][c] = cnt++; + u = nodes[u][c]; + } + terminate.set(u); + } + + std::vector m[20008]; + +public: + std::vector> suggestedProducts(const std::vector& products, const std::string& searchWord) { + if (searchWord.empty()) + return {}; + for (const std::string& s : products) + insert(s); + std::string buffer {searchWord.front()}; + buffer.reserve(3072); + std::function dfs = [&](int u) { + if (terminate.test(u)) + m[u].push_back(buffer); + for (int i = 0; i < 26; ++i) { + if (!nodes[u][i]) + continue; + buffer.push_back(i + 'a'); + + dfs(nodes[u][i]); + m[u].insert(m[u].end(), m[nodes[u][i]].begin(), m[nodes[u][i]].end()); + + buffer.pop_back(); + } + }; + + if (!nodes[0][id(searchWord.front())]) + return {searchWord.length(), std::vector()}; + dfs(nodes[0][id(searchWord.front())]); + int u = 0; + std::vector> ret; + for (char ch : searchWord) { + if (!nodes[u][id(ch)]) { + while (ret.size() < searchWord.length()) + ret.emplace_back(); + return ret; + } + u = nodes[u][id(ch)]; + if (m[u].size() > 3) { + ret.push_back({m[u][0], m[u][1], m[u][2]}); + } else { + ret.push_back(m[u]); + } + } + return ret; + } +}; + +int main() { + auto* s = new Solution(); + auto r = s->suggestedProducts({"mobile","mouse","moneypot","monitor","mousepad"}, "mouse"); + return 0; +} diff --git a/cpp/2206/CMakeLists.txt b/cpp/2206/CMakeLists.txt index 4ac96ac..5906648 100644 --- a/cpp/2206/CMakeLists.txt +++ b/cpp/2206/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2206) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2206 220618.cpp) +ADD_EXECUTABLE(2206 220619.cpp)