728x90
반응형

기본적인 스택 문제이다.

for _ in range(int(input())):
    s = input()
    stack, ok = [], 1
    for c in s:
        if c == '(':
            stack.append(c)
        else:
            if stack == []:
                ok = 0
            else:
                stack.pop()
    print("YES" if stack == [] and ok else "NO")

아래 풀이는 예전에 내가 자료구조 공부하기 전에 풀었던 방식이다.

입력에 '()'가 없을 때까지 replace를 통해 '()'을 공백으로 바꿔준다.

'()'가 없는데 문자열의 길이가 0보다 크다면 VPS가 아니므로 NO, 길이가 0이라면 VPS이므로 YES를 출력한다.

for _ in range(int(input())):
    a = input()
    while '()' in a:
        a = a.replace('()', '')
    if len(a) > 0:
        print('NO')
    else:
        print('YES')

 

728x90
반응형

+ Recent posts