ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ๊ด„ํ˜ธ ํšŒ์ „ํ•˜๊ธฐ

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

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ๊ด„ํ˜ธ ํšŒ์ „ํ•˜๊ธฐ

 

 

 ๋ฌธ์ œ ์„ค๋ช…

 

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

 

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

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

programmers.co.kr

 

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

 

์ด๋Ÿฐ ๊ด„ํ˜ธ ๋ฌธ์ œ๋Š” ์Šคํƒ์ด ๊ฑฐ์˜ ๊ณ ์ •์ธ ๊ฒƒ ๊ฐ™๋‹ค.

์—ฌ๋Š ๋•Œ์™€ ๊ฐ™์ด removeFirst์™€ removeLast๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๋ฌธ์ œ๋ฅผ ํ’€์—ˆ๋‹ค.

 

import Foundation

func solution(_ s:String) -> Int {
    var result = 0
    var changedArr = Array(s).map{ String($0) }
    var stack: [String] = []
    for i in 0..<s.count {
        for j in changedArr {
            if stack.isEmpty {
                stack.append(j)
            } else {
                if stack.last! == "(" && j == ")" || stack.last! == "{" && j == "}" || stack.last! == "[" && j == "]" {
                    stack.removeLast()
                } else {
                    stack.append(j)
                }
            }
        }
        result += stack.isEmpty ? 1 : 0
        stack = []
        changedArr.append(changedArr.removeFirst())
    }
    return result
}