#include #include #include #include #include class Solution { public: static std::string longestWord(const std::vector& words) { std::unordered_set s(words.begin(), words.end()); std::string ans = ""; int ansLen = 0; std::queue q; q.push(""); while (!q.empty()) { std::string x = q.front(); q.pop(); int xLen = x.length(); for (char c = 'a'; c <= 'z'; ++c) { std::string nx = x + c; if (s.count(nx)) { if (nx.length() > ansLen) { ans = nx; ansLen = nx.length(); } q.push(nx); } } } return ans; } }; int main() { std::cout << Solution::longestWord({"a","banana","app","appl","ap","apply","apple"}); return 0; }