본문 바로가기
알고리즘

[Swift] LeetCode - 819. Most Common Word

by 고고 2022. 2. 14.

문제: https://leetcode.com/problems/most-common-word/submissions/

 

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

 

 

import Foundation

class Solution {
    func mostCommonWord(_ paragraph: String, _ banned: [String]) -> String {
        var dict = [String: Int]()
        let words = paragraph.split(omittingEmptySubsequences: true, whereSeparator: { ", ".contains($0) })
        
        for word in words {
            let word = word.lowercased().filter { "abcdefghijklmnopqrstuvwxyz".contains($0) }
            
            if !banned.contains(word) {
                if dict[word] == nil {
                    dict[word] = 1
                } else {
                    dict[word]! += 1
                }
            }
        }
        
        for word in dict.sorted(by: { $0.value > $1.value }) {
            return word.key
        }
        
        return ""
    }
}

댓글