๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“– Problem Solution/Programmers

[Swift] 2019 ์นด์นด์˜ค ๊ฐœ๋ฐœ์ž ๊ฒจ์šธ ์ธํ„ด์‰ฝ ๋ถˆ๋Ÿ‰ ์‚ฌ์šฉ์ž

by Fomagran ๐Ÿ’ป 2021. 6. 26.
728x90
๋ฐ˜์‘ํ˜•

Problem

 

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๋ถˆ๋Ÿ‰ ์‚ฌ์šฉ์ž

๊ฐœ๋ฐœํŒ€ ๋‚ด์—์„œ ์ด๋ฒคํŠธ ๊ฐœ๋ฐœ์„ ๋‹ด๋‹นํ•˜๊ณ  ์žˆ๋Š” "๋ฌด์ง€"๋Š” ์ตœ๊ทผ ์ง„ํ–‰๋œ ์นด์นด์˜ค์ด๋ชจํ‹ฐ์ฝ˜ ์ด๋ฒคํŠธ์— ๋น„์ •์ƒ์ ์ธ ๋ฐฉ๋ฒ•์œผ๋กœ ๋‹น์ฒจ์„ ์‹œ๋„ํ•œ ์‘๋ชจ์ž๋“ค์„ ๋ฐœ๊ฒฌํ•˜์˜€์Šต๋‹ˆ๋‹ค. ์ด๋Ÿฐ ์‘๋ชจ์ž๋“ค์„ ๋”ฐ๋กœ ๋ชจ์•„ ๋ถˆ๋Ÿ‰

programmers.co.kr


Solution

 

1. ๋ถˆ๋Ÿ‰ ์‚ฌ์šฉ์ž์™€ ์œ ์ € ์•„์ด๋””๋ฅผ ๋น„๊ตํ•œ๋‹ค.

 

func isEqual(userId:String,bannedId:String) -> Bool {
    if userId.count != bannedId.count { return false }
    
    let uid = userId.map{String($0)}
    let bid = bannedId.map{String($0)}
    
    for (i,b) in bid.enumerated() {
        if b != "*" && uid[i] != bid[i]  {
            return false
        }
    }
    return true
}

 

2. ๋น„๊ตํ•œ ์•„์ด๋”” ์ค‘ ํ•ด๋‹นํ•˜๋Š” ์•„์ด๋””๋ฅผ ๋”ฐ๋กœ ๋ชจ์•„๋†“๋Š”๋‹ค.

 

func findBanIdEqualUserId(userId:[String],banId:[String]) -> [[Int]] {
    var banArray = Array(repeating: [Int](), count: banId.count)
    
    for (i,uid) in userId.enumerated() {
        for (j,bid) in banId.enumerated() {
            if isEqual(userId: uid, bannedId: bid) {
                banArray[j].append(i)
            }
        }
    }
    return banArray
}

 

3. ๋ถˆ๋Ÿ‰์‚ฌ์šฉ์ž๋“ค์˜ ๋ชจ๋“  ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๊ตฌํ•œ๋‹ค.

 

func insertBanIdsToResult(banArray:[[Int]],banIds:Set<Int>,result:inout Set<[Int]>,current:Int) {
    for id in banArray[current] {
        var newBanIds = banIds
        newBanIds.insert(id)
        if current != banArray.count - 1 {
            insertBanIdsToResult(banArray:banArray,banIds: newBanIds,result:&result ,current: current+1)
        }else if newBanIds.count == banArray.count {
            result.insert(newBanIds.sorted())
        }
    }
}

 

4. ๊ฒฝ์šฐ์˜ ์ˆ˜์˜ ๊ฐฏ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

 

return result.count

Source Code

 

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€