상세 컨텐츠

본문 제목

819. Most Common Word

Developer/LEETCODE

by cepiloth 2021. 9. 5. 21:46

본문

728x90
반응형

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

 

Most Common Word - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

난이도 : easy

문제

금지된 단어를 제외한 가장 흔하게 등장하는 단어를 출력하라. 대소문자 구분을 하지 않으며, 구두점(마침표, 쉼표 등) 또한 무시한다.

주어진 paragraph 에서 알파벳이면 소문자로 치환한다. banned 문자열을 unorded_set 자료구조를 사용하여 삽입하고 paragraph 문자자열을 순회하면서 셋의 함수인 count 를 통하여 금지어인지 확인하고 금지어가 아니면 map 자료형에 키와 벨류를 삽입한다. 이때 증감 연산자를 사용하여 빈도수가 가장 높은 문자를 반환 하도록 한다.

 

코드

class Solution {
public:
    string mostCommonWord(string paragraph, vector<string>& banned) {
        
        // 주어진 pragrpaph 에서 공백이 아니고 알파벳이면 소문자로 치환

        for (auto& c:paragraph)
            c = isalpha(c) ? tolower(c) : ' ';
        
        string str, res;
        unordered_map<string, int> freq;
        unordered_set<string> b(banned.begin(), banned.end());
        
        stringstream ss(paragraph);

        // stringstream 으로 문자열을 분리하면서 unorded_map 키와 벨류를 추가
        // value 값이 크다면 가장 빈도가 높은 문자로 판단.
        
        while(ss >> str)
            if(b.count(str) == 0 && freq[res] < ++freq[str])
                res = str;
        
        return res;
    }
};
728x90
반응형

'Developer > LEETCODE' 카테고리의 다른 글

관련글 더보기

댓글 영역