ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ํŠœํ”Œ(Swift)

2022. 10. 12. 15:08ใ†ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค-Swift

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ํŠœํ”Œ(Swift)

 

 

 ๋ฌธ์ œ ์„ค๋ช…

 

https://school.programmers.co.kr/learn/courses/30/lessons/64065

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

 

 ๋‚˜์˜ ํ’€์ด

 

๋ฌธ์ œ๋ฅผ ์ดํ•ดํ•˜๋ฉด ์Šค์Šค๋กœ ํ™•์‹ ์„ ๊ฐ–๊ณ  ํ’€์ด๋ฅผ ํ•˜๋Š” ๊ฒƒ์ด ํ˜„์žฌ ๋‚˜์—๊ฒŒ ํ•„์š”ํ•˜๋‹ค. 

๋ฌธ์ œ๋Š” ํŠœํ”Œ์˜ ์ •์˜๋ฅผ ์„ค๋ช…ํ•œ ํ›„์— ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง€๋Š” ํŠœํ”Œ์„ ์„ค๋ช…ํ•˜๋Š”๋ฐ ํ›„์ž์— ํฌ์ปค์Šค๋ฅผ ๋‘ฌ์„œ Input๊ณผ output์„ ๋ถ„์„ํ•ด์„œ ํ’€์ด๋ฐฉ๋ฒ•์„ ์ฐพ์•„์•ผํ•œ๋‹ค.

 

์ด ๋ฌธ์ œ์˜ ํ•ต์‹ฌ์€ count๊ฐ€ ์ ์€ ๊ฒƒ๋ถ€ํ„ฐ ์ˆœ์„œ๋ฅผ ๊ฐ€์ง„๋‹ค๋Š” ๊ฒƒ์ด๋‹ค.

์ด๋ฅผ ์ด์šฉํ•ด์„œ sortํ•œ ํ›„์— ์ฐจ๋ก€๋Œ€๋กœ ๋ฐฐ์—ด์— ๋‹ด์•˜๋‹ค.

 

import Foundation

func solution(_ s:String) -> [Int] {
    var answer: [Int] = []
    let s = s.replacingOccurrences(of: "{", with: "")
    let tupleStr = s.components(separatedBy: "},").map{ $0.replacingOccurrences(of: "}", with: "")}
    let tuple = tupleStr.map{ $0.components(separatedBy: ",")}.sorted(by: {$0.count < $1.count})
    
    tuple.forEach { tup in
        tup.forEach { num in
            let number = Int(num)!
            if !answer.contains(number) {
                answer.append(number)   
            }     
        }
    }
    return answer
}

 

 

 

 ๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด

 

split์„ ํ†ตํ•ด์„œ ๋ฌธ์ž์—ด์„ ์ชผ๊ฐœ๊ณ  Set์˜ subtracting์„ ์ด์šฉํ•ด์„œ ํ•ด๊ฒฐํ•œ ํ’€์ด์ด๋‹ค.

whereSeparator์—๋Š” true๋‚˜ false๊ฐ€ ์˜ค๋Š” ์กฐ๊ฑด์‹์ด ์˜ค๋Š”๋ฐ true๋ผ๋ฉด ๋ถ„๋ฆฌ์ž๊ฐ€ ๋˜์–ด Array<SubString>์„ ๋งŒ๋“ ๋‹ค.

 

์ด ํ’€์ด์˜ ์žฌ๋ฐŒ๋Š” ์ ์€ ํ•œ๋ฒˆ ๋ถ„๋ฆฌ์‹œํ‚ค๊ณ  map์„ ํ†ตํ•ด ๋ถ„๋ฆฌ๋œ ๊ฐ๊ฐ์— ๋Œ€ํ•ด ๋˜ ๋ถ„๋ฆฌ๋ฅผ ์‹œํ‚จ ํ›„ Int๋กœ ๋งคํ•‘ํ•˜๋Š” ์ ์ด๋‹ค. 

 

ํ•œ๋ฒˆ์— ๋ชจ๋“  ๊ฑธ ์ชผ๊ฐœ์ž๋ผ๊ณ  ์ƒ๊ฐํ–ˆ์—ˆ๋Š”๋ฐ ๋ถ„๋ฆฌ๋œ ๊ฒƒ์„ ํ† ๋Œ€๋กœ ๋˜ ์ชผ๊ฐœ๋Š” ์ƒ๊ฐ์ด ์žฌ๋ฐŒ์–ด์„œ ๊ฐ€์ ธ์™”๋‹ค.

 

import Foundation

func solution(_ s:String) -> [Int] {
    var answer: [Int] = []
    
    var tuple = s.split(omittingEmptySubsequences: true, whereSeparator: { "{".contains($0) }).map {
        $0.split(omittingEmptySubsequences: true, whereSeparator: { "},".contains($0) }).map { Int($0)! }
    }
    
    tuple.sort(by: {$0.count < $1.count})
    
    tuple.forEach { tup in
        answer.append(Array(Set(tup).subtracting(answer)).first!)
    }
            
    
    
    return answer
}