๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm๐Ÿฐ/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] Swift ํŠœํ”Œ 2019 ์นด์นด์˜ค implementation

by Jouureee 2022. 4. 14.

๋ฌธ์ œ :

https://programmers.co.kr/learn/courses/30/lessons/64065?language=swift 

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ํŠœํ”Œ

"{{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

 

๋ถ„์„ :

string ๋ฐฐ์—ด์„ ๋Œ๋ฉฐ "{" ๊ฐ€ ๋‚˜ํƒ€๋‚ฌ์„๋•Œ "}"๊ฐ€ ๋‚˜ํƒ€๋‚˜๊ธฐ ์ „๊นŒ์ง€ ์›์†Œ๋ฅผ ํ•˜๋‚˜์”ฉ ๋‹ด๋Š”๋‹ค.

result array์— ๊ฐ’์ด ์—†์„๋•Œ๋งŒ ์›์†Œ๋ฅผ ๋‹ด์•„ ๋ฆฌํ„ดํ•˜๋„๋ก ํ–ˆ๋Š”๋ฐ ์ด ๋ถ€๋ถ„์—์„œ O(n^2)์„ ์‚ฌ์šฉํ•ด ๋˜๊ฒŒ ๋น„ํšจ์œจ์ ์ด๋ผ๋Š” ์ƒ๊ฐ์ด ๋“ค์—ˆ๋‹ค. 

๋‹ค๋ฅธ ์‚ฌ๋žŒ๋“ค ํ’€์ด๋ฅผ ๋ณด๋‹ˆ component ๋˜๋Š” split๋ฅผ ํ™œ์šฉํ•ด ์‰ฝ๊ฒŒ ๋ฐฐ์—ด์„ ๋ถ„๋ฆฌํ•˜๊ณ  ๊ณ„์‚ฐํ•˜๋Š”๊ฒƒ ๊ฐ™์•˜๋‹ค.

 

Swift ์ฝ”๋“œ :

//
//  main.swift
//  SOMA๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป
//
//  Created by JoSoJeong on 2022/04/14.
//

import Foundation

func solution(_ s:String) -> [Int] {
    var str = s
    var reArr = Array(repeating: [Int](), count: 501)
    str.removeFirst()
    str.removeLast()
    var arr = Array(str)
    var result = [Int]()
    var i = 0
    var length = 0
    
    while i < arr.count {
        if arr[i] == "{" {
            length += 1
            var number = ""
            while arr[i] != "}"{
                i += 1
                if arr[i] == "}" {
                    reArr[length].append(Int(number)!)
                }
                else if arr[i] == "," {
                    reArr[length].append(Int(number)!)
                    number = ""
                }

                if 48 <= arr[i].asciiValue! && arr[i].asciiValue! < 57 {
                    number += "\(arr[i])"
                }
            }
        }
        i += 1
    }
    reArr = reArr.filter { !$0.isEmpty }
    reArr.sort { $0.count < $1.count }
    
    for i in reArr {
        if i.isEmpty { continue }
        if i.count == 1 { result.append(i[0]) }
        else {
            for num in i {
                if !result.contains(num) {
                    result.append(num)
                }
            }
        }
    }
    return result
}

 

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

import Foundation
func solution(_ s:String) -> [Int] {
    var s = s
    var answer = [Int]()
    s.removeFirst(2)
    s.removeLast(2)

    s.components(separatedBy: "},{")
        .map { $0.components(separatedBy: ",").map { Int($0)! } }
        .sorted { $0.count < $1.count }
        .forEach {
            $0.forEach {
                if !answer.contains($0) {
                    answer.append($0)
                }
            }
    }
    return answer
}

 

๊ฒฐ๊ณผ :

๋Œ“๊ธ€