본문 바로가기

Algorithm/String

(C++) - LeetCode (easy) 819. Most Common Word

반응형

https://leetcode.com/problems/most-common-word/description/

 

Most Common Word - LeetCode

Can you solve this real interview question? Most Common Word - Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and tha

leetcode.com

구현 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

단어와 빈도수를 저장할 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;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.