[LeetCode]가장 흔한 단어 - 복습

Inhwan98·2023년 10월 30일
0

알고리즘

목록 보기
1/2

문제

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

  • Example 1:
Input: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]

Output: "ball"

Explanation: 
"hit" occurs 3 times, but it is a banned word.
"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. 
Note that words in the paragraph are not case sensitive,
that punctuation is ignored (even if adjacent to words, such as "ball,"), 
and that "hit" isn't the answer even though it occurs more because it is banned.
  • Example 2:
Input: paragraph = "a.", banned = []
Output: "a"

코드

class Solution {
private:
    string word;
    multiset<string> wordMultiSet;

public:
    string mostCommonWord(string paragraph, vector<string>& banned)
    {
        queue<char> que;

        for (auto iter = paragraph.begin(); iter != paragraph.end(); ++iter)
        {
            //알파뱃이라면
            if (isalpha(*iter))
            {
                *iter = tolower(*iter);

                que.push(*iter);
                //다음이 마지막이라면
                if ((iter + 1) == paragraph.end())
                {
                    InsertWord(que, banned);
                }
            }
            //알파벳이 아니라면
            else
            {
                InsertWord(que, banned);
            }       
        }

        int maxCount = 0;
        string result;
        for (auto iter = wordMultiSet.begin(); iter != wordMultiSet.end(); ++iter)
        {
            int count = wordMultiSet.count(*iter);
            if (count >= maxCount)
            {
                maxCount = count;
                result = *iter;
            }
        }
        return result;
    }

    void InsertWord(queue<char> &que, vector<string>& banned)
    {
        if (que.empty()) return;

        while (!que.empty())
        {
           word.push_back(que.front()); 
            que.pop();
        }

        auto banword = find(banned.begin(), banned.end(), word);
        //밴 단어에 포함될 때
        if (banword != banned.end())
        {
            while (!que.empty())
            {
                que.pop();
            }
        }
        else
        {
            wordMultiSet.insert(word);
        }
        
        word.clear();
    
    }

};

결과

Runtime 10ms / Memory 8.4mb
https://leetcode.com/problems/most-common-word/submissions/1087534905/


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

profile
코딩마스터

0개의 댓글