add: 220417-CN [cpp]

This commit is contained in:
eat-swap 2022-04-17 13:06:33 +08:00
parent 81ee098e42
commit 9ac09a4f1d
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 30 additions and 1 deletions

29
cpp/2204/220417-CN.cpp Normal file
View File

@ -0,0 +1,29 @@
#include <string>
#include <vector>
#include <cctype>
#include <iostream>
#include <algorithm>
#include <unordered_map>
class Solution {
public:
static std::string mostCommonWord(std::string paragraph, const std::vector<std::string>& banned) {
std::unordered_map<std::string, int> freq;
std::for_each(paragraph.begin(), paragraph.end(), [](char& c){ c = std::tolower(c); });
paragraph.push_back('.');
const char* ptr = paragraph.c_str();
for (const char* p1 = ptr, * p2 = ptr; *p2; ++p2) {
if (!std::isalpha(*p2)) {
if (p2 - p1)
++freq[std::string(p1, p2)];
p1 = 1 + p2;
}
}
std::for_each(banned.cbegin(), banned.cend(), [&freq](const std::string& str) { freq.erase(str); });
return std::max_element(freq.cbegin(), freq.cend(), [](const std::pair<std::string, int>& x, const std::pair<std::string, int>& y) { return x.second < y.second; })->first;
}
};
int main() {
std::cout << Solution::mostCommonWord("Bob hit a ball, the hit BALL flew far after it was hit.", {"hit"});
}

View File

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