๋ฌธ์ :
https://programmers.co.kr/learn/courses/30/lessons/64065?language=swift
๋ถ์ :
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
}
๊ฒฐ๊ณผ :
๋๊ธ