괄호_9012번

[Python, Go] 백준 9012번 풀이

괄호

  • 괄호의 쌍이 맞게 이루어져있는지 찾아내는 문제이다.

  • “(“괄호와 “)” 괄호의 개수를 세는것에서 끝나면 안된다.

  • 스택에 “(“ 가 들어왔을때 저장하고 “)” 와 만나면 스택에서 하나를 제거하는 방법으로 쌍을 맞춰주었다.

  • 가장 먼저 들어오는 문자열이 “)” 이라면 쌍이 맞을 수 없으므로 NO 를 리턴하며, 문자열 모두를 파악한 후 stack이 비어있다면 YES 그렇지 않다면 NO 이다

  • Python 풀이

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import sys

n = int(sys.stdin.readline())


def vps(li):
stack = []

if li[0] == ")":
return "NO"
else:
for s in li:
if s == "(":
stack.append(s)
elif s == ")" and stack != []:
stack.pop()
else:
return "NO"

if stack == []:
return "YES"
else: return "NO"

for i in range(n):
order = list(sys.stdin.readline().rstrip())
print(vps(order))
  • Go 풀이

    • Go 를 사용할때는 파이썬의 pop과같은 내장함수가 없으므로 “)”를 만났을때 슬라이스의 길이가 1인 경우와 그렇지 않은 경우를 나눠서 판단했다.
func vps(x string) string {
    var stack []string

    for idx, ch := range x {
        s := string(ch)
        if idx == 0 && s == ")" {
            return "NO"
        } else {
            if s == "(" {
                stack = append(stack, s)
            } else if s == ")" && stack != nil {
                length := len(stack)
                if length == 1 {
                    stack = nil
                } else {
                    stack = stack[:length-1]
                }
            } else {
                return "NO"
            }
        }
    }
    if stack == nil {
        return "YES"
    } else {
        return "NO"
    }
}

Full Code

Full Code - Python

Full Code - Go

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×