add: 220317-CN [cpp]

This commit is contained in:
Lam Haoyin 2022-03-17 21:48:40 +08:00
parent a321d557be
commit 4fcc7edb67
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 40 additions and 1 deletions

39
cpp/2203/220317-CN.cpp Normal file
View File

@ -0,0 +1,39 @@
#include <vector>
#include <string>
#include <queue>
#include <unordered_set>
#include <iostream>
class Solution {
public:
static std::string longestWord(const std::vector<std::string>& words) {
std::unordered_set<std::string> s(words.begin(), words.end());
std::string ans = "";
int ansLen = 0;
std::queue<std::string> 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;
}

View File

@ -3,4 +3,4 @@ PROJECT(2203)
SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2203 220317.cpp) ADD_EXECUTABLE(2203 220317-CN.cpp)