Potato
์•ˆ๋…•ํ•˜์„ธ์š”, ๊ฐ์žก๋‹ˆ๋‹ค?๐Ÿฅ” ^___^ ๐Ÿ˜บ github ๋ฐ”๋กœ๊ฐ€๊ธฐ ๐Ÿ‘‰๐Ÿป

Algorithm/Baekjoon

[๋ฐฑ์ค€] (Swift) 9012๋ฒˆ - ๊ด„ํ˜ธ

๊ฐ์ž ๐Ÿฅ” 2022. 1. 19. 16:06
๋ฐ˜์‘ํ˜•

 

๋ฌธ์ œ ๋งํฌ

https://www.acmicpc.net/problem/9012

๋ฐ˜์‘ํ˜•
 

9012๋ฒˆ: ๊ด„ํ˜ธ

๊ด„ํ˜ธ ๋ฌธ์ž์—ด(Parenthesis String, PS)์€ ๋‘ ๊ฐœ์˜ ๊ด„ํ˜ธ ๊ธฐํ˜ธ์ธ ‘(’ ์™€ ‘)’ ๋งŒ์œผ๋กœ ๊ตฌ์„ฑ๋˜์–ด ์žˆ๋Š” ๋ฌธ์ž์—ด์ด๋‹ค. ๊ทธ ์ค‘์—์„œ ๊ด„ํ˜ธ์˜ ๋ชจ์–‘์ด ๋ฐ”๋ฅด๊ฒŒ ๊ตฌ์„ฑ๋œ ๋ฌธ์ž์—ด์„ ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ ๋ฌธ์ž์—ด(Valid PS, VPS)์ด๋ผ๊ณ 

www.acmicpc.net


๋‚ด๊ฐ€ ํ‘ผ ํ’€์ด

์ดˆ๋ฐ˜์— ์ž…๋ ฅ๋ฐ›๋Š” line๋“ค์„ array์— ๋„ฃ์€ ํ›„, rightValue ๋ผ๋Š” ์ƒˆ๋กœ์šด array์— (, (, ), ์ด๋ ‡๊ฒŒ ํ•˜๋‚˜์”ฉ ๋„ฃ์–ด์ฃผ๊ณ , '('์™€ ')' ๋กœ ์Œ์ด ์ด๋ฃจ์–ด์ง€๋ฉด ์—†์• ์ฃผ๊ณ , ์ตœ์ข…์ ์œผ๋กœ rightValue ๋ฐฐ์—ด์˜ ๊ธธ์ด๊ฐ€ '0'์ด ๋˜๋ฉด YES๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜๋ ค๊ณ  ํ–ˆ๋‹ค. (์˜ˆ์ „์— ํŒŒ์ด์ฌ์œผ๋กœ ์ฝ”ํ…Œ๋ฅผ ๋ณผ๋•Œ๋Š” ์ด๋ ‡๊ฒŒ ํ–ˆ์—ˆ๋‹ค.) ๊ทผ๋ฐ,,, ์™œ์ธ์ง€ swift๋Š” pop๊ธฐ๋Šฅ์ด ํŒŒ์ด์ฌ์ฒ˜๋Ÿผ popleft, pop(0) ์ฒ˜๋Ÿผ ์™ผ์ชฝ ์˜ค๋ฅธ์ชฝ ์•„๋ฌด๋ ‡๊ฒŒ๋‚˜ pop ๋˜๋Š” ๊ธฐ๋Šฅ์ด ์ž์—ฐ์Šค๋Ÿฝ์ง€ ๋ชปํ•œ ๊ฒƒ ๊ฐ™์•˜๋‹ค. (์•„์ง swift์ดˆ๋ณด ๋ผ์„œ ๊ทธ๋Ÿฐ๊ฑธ ์ˆ˜๋„ ์žˆ์–ด์š”. ์–ด์ƒ‰ํ–ˆ๋‹ค...) 

์–ด์จ‹๋“  ๊ทธ๋ž˜์„œ, countํ•ด์ฃผ๋Š” ๋ฐฉ์‹์œผ๋กœ ์ฝ”๋“œ๋ฅผ ์งฐ๋‹ค.

import Foundation

let n = Int(readLine()!)!

for _ in 0..<n {
    let line = readLine()!
    var count = 0
    for char in line{
        if char == "(" {
            count += 1
        } else if char == ")" {
            count -= 1
            if count < 0 {
                break
            }
        }
        
    }
    print(count==0 ? "YES" : "NO")
}
๋ฐ˜์‘ํ˜•