()
가 몇개 들어있는지 센다음 그것을 합산해주면 되겠다!제한시간 초과로 실패
import sys
sys.stdin = open("input.txt")
T = int(input())
# 제한 시간 초과
for tc in range(1, T+1):
inp = input()
L = len(inp)
cnt_close = 0 # () 괄호가 닫혔는지 체크
cnt = 0 # 안에 () 가 몇개 들었는지 체크
result = 0 # 결과
for i in range(L) :
cnt = 0
cnt_close = 0
if inp[i] == "(" :
cnt_close +=1
for j in range(i+1, L) : # 그 다음부터 끝까지 확인 - 괄호 닫히는 거 체크
if inp[j] == "(" :
cnt_close +=1
if j < L-1 and inp[j+1] == ")" : # () 괄호 갯수세기
cnt+=1
else :
cnt_close -=1
if cnt_close == 0 :
result += cnt+1 if cnt!=0 else 0 # cnt 가 0이 아니면 cnt+1 로 더해지고, 아니면 0
break
print("#{} {}".format(tc, result))
아이디어
(
를 만나면 cnt +=1
)
를 만나면 cnt-=1 을 해줘서 cnt로 누적된 판의 갯수를 구하자
)
를 만날때 반응이 두가지 경우
(
가 바로 앞에 있었을 경우 - 레이저로 자른다)
가 바로 앞에 있을 경우 - 잘리고 남은 자투리 하나를 계산import sys
sys.stdin = open("input.txt")
T = int(input())
for tc in range(1, T+1):
inp = input()
cnt = 0
result =0
back=")"
for tmp in inp :
if tmp == "(" :
cnt+=1
else :
cnt -= 1
if back=="(" :
result += cnt # 잘리는 판의 갯수
else :
result+=1 # 판이 끝날때 남는 조각 1개
back=tmp #이전꺼
print("#{} {}".format(tc, result))
import sys
sys.stdin = open("input.txt")
T = int(input())
# 스택을 이용한 풀이
for tc in range(1, T+1):
inp = input()
stack = []
result = 0
back = 0
for tmp in inp :
if tmp == "(" :
stack.append(tmp)
else :
stack.pop()
if back != tmp :
result += len(stack) # 쌓여있는 판 갯수
else :
result +=1
back = tmp
print("#{} {}".format(tc, result))