https://www.acmicpc.net/problem/4949
from sys import stdin
while True:
s = stdin.readline().rstrip()
if s == ".":
break
ans = 1
stack = []
for ch in s:
if ch == "(" or ch == ")" or ch == "[" or ch == "]":
if ch == "(" or ch == "[":
stack.append(ch)
elif stack and ch == ")" and stack[-1] == "(":
stack.pop()
elif stack and ch == "]" and stack[-1] == "[":
stack.pop()
else:
ans = 0
break
if ans and len(stack) == 0:
print("yes")
else:
print("no")
입력받은 문자열은 오른쪽 끝만 strip() 해주기
"." 이면 종료 설정
나머지는 stack 을 이용해서 괄호가 올바른지 확인
여는 괄호면 append
닫는 괄호면 stack 의 top 값과 매치되는지 확인해서 pop
매치되지 않거나 남은 괄호가 있다면 no 출력
https://www.acmicpc.net/problem/5525
from sys import stdin
N = int(stdin.readline())
M = int(stdin.readline())
S = stdin.readline().strip()
ans = 0
P = "OI"*N
for i in range(M):
if N*2 >= M:
break
if S[i] == "I":
if S[i+1:i+1+N*2] == P:
ans += 1
print(ans)
처음 I 를 제외한 OI 의 개수가 N 과 같다는 점을 이용
I 를 만나면 이후에 N 개의 OI 가 오는지 확인해서 ans + 1
for 문 + 슬라이싱 때문에 시간초과 돼서 50 점인 것 같다...
from sys import stdin
N = int(stdin.readline())
M = int(stdin.readline())
S = stdin.readline().strip()
ans = 0
count = 0
i = 1
while i < M - 1:
if S[i-1] == "I" and S[i] == "O" and S[i+1] == "I":
count += 1
if count == N:
count -= 1
ans += 1
i += 1
else:
count = 0
i += 1
print(ans)
IOI 의 개수가 N 과 같다는 점을 이용
IOI 의 개수를 세서 N 개가 되면 ans + 1 해주는 단순한 방법
슬라이싱으로 안돼서 슬라이딩 윈도우도 생각해보고 했지만
내가 너무 어렵게 생각한듯...