반응형
https://leetcode.com/problems/most-common-word/description/
구현 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
단어와 빈도수를 저장할 map frequencyMap과 ban당한 단어를 저장할 map bannedMap을 선언해 줍니다.
📔 풀이과정
1. 문단의 구분자에 따라 단어를 나눠줍니다. split함수가 따로 없으므로 for loop를 수행해 vector<string>형태로 반환하도록 구현해줍니다. 이를 words라는 vector에 저장해줍니다.
2. words의 원소를 돌며 ban당한 단어거나 빈 단어가 아니라면 frequencyMap에 단어에 맞는 빈도수를 올려줍니다.
3. frequencyMap의 maxElement를 찾아줍니다. C++11부터 지원되는 lamda함수를 사용해 value가 가장 큰 원소를 찾습니다.
📔 정답 출력 | 반환
maxElement의 first인 단어를 반환합니다.
📕 Code
📔 C++
class Solution {
public:
vector <string> split(string paragraph) {
vector <string> result;
string word;
for(auto c : paragraph) {
if(c == '!' || c == '?' || c == '\'' || c == ',' || c == ';' || c == '.' || c == ' ') {
result.push_back(word);
word = "";
continue;
}
word += tolower(c);
}
result.push_back(word);
return result;
}
string mostCommonWord(string paragraph, vector<string>& banned) {
map <string, int> frequencyMap;
map <string, int> bannedMap;
for(auto b : banned) {
bannedMap[b] = 1;
}
vector <string> words = split(paragraph);
for(string &word: words) {
if(bannedMap[word] || word == "") continue;
frequencyMap[word]++;
}
auto maxElement = max_element(frequencyMap.begin(), frequencyMap.end(),
[] (const auto& a, const auto& b) {
return a.second < b.second;
});
return maxElement->first;
}
};
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > String' 카테고리의 다른 글
(C++) - LeetCode (easy) 844. Backspace String Compare (0) | 2023.07.31 |
---|---|
(C++) - LeetCode (easy) 824. Goat Latin (0) | 2023.07.24 |
(C++) - LeetCode (easy) 557. Reverse Words in a String III (0) | 2023.04.19 |
(C++) - LeetCode (easy) 541. Reverse String II (0) | 2023.04.16 |
(C++) - LeetCode (easy) 521. Longest Uncommon Subsequence I (0) | 2023.04.14 |