๋ฌธ์ :
https://programmers.co.kr/learn/courses/30/lessons/60058
๋์ด๋ : level2
๋ถ์ :
์ฃผ์ด์ง ์๊ฑด์ ์ ์ฝ๊ณ ์๊ตฌ ์ฌํญ๋๋ก ๊ตฌํํ๋ ๋ฌธ์ ์๋ค. ์ด๋ฐ ๋ฌธ์ ์ผ์๋ก ์ค๊ณ๋ฅผ ์ ํ์ง ์์ผ๋ฉด ๋ก์ง์ด ๊ผฌ์ด๊ธฐ ์ฌ์ ์ด๋ ค์ด๊ฑฐ ๊ฐ๋ค(๋ํํ ๋ง ์ผ์ง๋ ๋ชจ๋ฅธ๋ค .. ใ )
1,2,3,4๋ฒ์ ์ฐจ๋ก๋๋ก ๊ตฌํํด์ฃผ๋ ํ์ํ๊ฑด ํจ์๋ก ๋ถ๋ฆฌํด ์์ฑํ๋๊ฒ์ด ์ข๋ค ํ๋จ ๋ค์๋ค.
๋ฐ๋ผ์ 1๋ฒ์ isEmpty๋ก ๊ฒ์ฌํ์๋ค.
2๋ฒ์ recursive ํจ์ ์์์ ๋ชจ๋ ๋ฌธ์์ด์ ๋๋ฉฐ "(" ์์ ")"์๋ฅผ ๋น๊ตํด ๊ฐ์๋(๊ท ํ์กํ ๊ดํธ ๋ฌธ์์ด) u, ๊ทธ ์ดํ์ ๋ฌธ์๋ฅผ v๋ก ๋ถ๋ฆฌํ์๋ค.
3๋ฒ์ check()ํจ์๋ฅผ ํตํด ์ฌ๋ฐ๋ฅธ ๊ดํธ ๋ฌธ์์ด์ธ์ง ํ์ธํ๋ค. ๊ฒ์ฌํ ๋ฌธ์์ด ์ฒซ๋ฒ์งธ ์์๋ถํฐ "("์ผ ๊ฒฝ์ฐ stack์ ๋ฃ๊ณ , ")"์ผ ๊ฒฝ์ฐ stack์ ์์ธ ๋ฌธ์๊ฐ "("์ธ์ง ํ์ธํ๋ฉฐ O(n)์ ์๊ฐ ๋ณต์ก๋๋ฅผ ๊ฐ์ง๋ค.
4๋ฒ์ ์ฌ๋ฐ๋ฅธ ๋ฌธ์๊ฐ ์๋๊ฒฝ์ฐ ๋ถ๊ธฐํ์ฌ ์ฒ๋ฆฌํ๋ค. ์ด ๊ฒฝ์ฐ๋ฅผ ์ดํดํ์ง ๋ชปํด ๋ค๋ฅธ ๋ธ๋ก๊ทธ๋ฅผ ์ฐธ๊ณ ํ์ฌ ํ์๋ค !!
newString ๋ณ์๋ฅผ ํ๋ ๋ง๋ค์ด "("๋ฅผ ๋ถ์ธ ๋ค 4-2๋ฒ์ ์ํํ ๋ v๋ฅผ ์ฌ๊ท๋ฅผ ๊ฑฐ์ณ ์ฌ๋ฐ๋ฅธ ๋ฌธ์์ด๋ก ๋ฐ๊พผ๋ค. ๊ทธ ๋ค ")"๋ฅผ ๋ถ์ด๊ณ
4-4๋ฒ์ธ u์ ์ฒซ๋ฒ์งธ, ๋ง์ง๋ง ๋ฌธ์๋ฅผ ์ ๊ฑฐํ๋ค u ์คํธ๋ง์ ์์๋ฅผ "(" -> ")", ")" -> "("๋ก ๋ฐ๊ฟ newString ๋ค์ ๋ฐ๊พผ ์์๋ค์ ๋ถ์ฌ ๋ฐํํ๋ค.
Swift ์ฝ๋ :
//
// main.swift
// SOMA๐ฉ๐ป๐ป
//
// Created by JoSoJeong on 2022/04/14.
//
import Foundation
func check(_ s: String) -> Bool {
if s.isEmpty { return true }
var s = s
var stack = [String]()
while !s.isEmpty {
let x = String(s.removeFirst())
if stack.isEmpty {
stack.append(x)
}else if stack.last! == "(" && x == ")" {
stack.removeLast()
}else {
stack.append(x)
}
}
return stack.isEmpty
}
func recursive(_ p: String) -> String {
if p.isEmpty { return "" }
else if check(p) {
return p
}
var leftCnt = 0
var rightCnt = 0
var u = ""
var v = ""
for (idx, i) in p.enumerated() {
if i == "(" {
leftCnt += 1
u += "("
}else if i == ")" {
rightCnt += 1
u += ")"
}
if leftCnt == rightCnt {
v = p.substring(from: idx+1, to: p.count-1)
if(check(u)) { // ์ฌ๋ฐ๋ฅธ ๋ฌธ์์ด์ธ์ง
return u + recursive(v)
}else { // ์ฌ๋ฐ๋ฅธ ๊ดํธ ๋ฌธ์์ด์ด ์๋๋ฏ๋ก
let newString = "(" + recursive(v) + ")"
u.removeFirst()
u.removeLast()
//๋๋จธ์ง ๊ดํธ ๋ฐฉํฅ ๋ค์ง๊ธฐ
u = u.map {
if $0 == "(" { return ")" }
else { return "(" }
}.reduce(""){$0 + $1}
return newString + u
}
}
}
return ""
}
func solution(_ p:String) -> String {
return recursive(p)
}
extension String {
func substring(from: Int, to: Int) -> String {
guard from < count, to >= 0, to - from >= 0 else {
return ""
}
// Index ๊ฐ ํ๋
let startIndex = index(self.startIndex, offsetBy: from)
let endIndex = index(self.startIndex, offsetBy: to + 1)
// ํ์ฑ
return String(self[startIndex ..< endIndex])
}
}
๊ฒฐ๊ณผ :
'Algorithm๐ฐ > ํ๋ก๊ทธ๋๋จธ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ํ๋ก๊ทธ๋๋จธ์ค] Swift ์์ ์ต๋ํ (0) | 2022.04.14 |
---|---|
[ํ๋ก๊ทธ๋๋จธ์ค] Swift ํํ 2019 ์นด์นด์ค implementation (0) | 2022.04.14 |
[ํ๋ก๊ทธ๋๋จธ์ค] Swift 2018 ์นด์นด์ค ๋ด์ค ํด๋ฌ์คํฐ๋ง implementation (0) | 2022.04.13 |
[ํ๋ก๊ทธ๋๋จธ์ค] Swift 2020 ์นด์นด์ค ์ธํด์ญ ํคํจ๋ ๋๋ฅด๊ธฐ (0) | 2022.04.08 |
[ํ๋ก๊ทธ๋๋จธ์ค] ํ๊ฒ ๋๋ฒ DFS C++ (0) | 2022.03.25 |
๋๊ธ