본문 바로가기
알고리즘

[Swift] 프로그래머스 - 카카오 튜플

by 고고 2022. 2. 11.

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

 

코딩테스트 연습 - 튜플

"{{2},{2,1},{2,1,3},{2,1,3,4}}" [2, 1, 3, 4] "{{1,2,3},{2,1},{1,2,4,3},{2}}" [2, 1, 3, 4] "{{4,2,3},{3},{2,3,4,1},{2,3}}" [3, 2, 4, 1]

programmers.co.kr

 

 

 

차집합은 다른 분의 풀이를 보고 이게 더 깔끔해보이겠다 싶어서 수정하였습니다.

import Foundation

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

solution("{{2},{2,1},{2,1,3},{2,1,3,4}}") // [2, 1, 3, 4]
//solution("{{1,2,3},{2,1},{1,2,4,3},{2}}") // [2, 1, 3, 4]
//solution("{{20,111},{111}}") // [111, 20]
//solution("{{123}}") // [123]
//solution("{{4,2,3},{3},{2,3,4,1},{2,3}}") //     [3, 2, 4, 1]

 

댓글