-풀이
import sys
input = sys.stdin.readline
for i in range(int(input())):
s = input().rstrip()
result = True
while len(s) > 0:
#시작 문자열 100이 들어가 있으면 100제외 슬라이싱
if s.startswith("100"):
s = s[3:]
while len(s)>0 and s.startswith("0"): #0+에 0이 계속나오면
s=s[1:] #0제외 슬라이싱
if len(s)==0: #뒤에 1이 무조건 하나는 나와야하므로 False
result = False
break
s=s[1:] #맨 처음 '1'이 나오는 경우 1제거
#----------------100+1----------만족-----
while len(s)>0 and s.startswith("1"):
if len(s)>=3 and s[1]=="0" and s[2]=="0":
break
else:
s=s[1:]
#01로 시작
elif s.startswith("01"):
s=s[2:] #01제거
else:
result=False
break
if result: print("YES")
else: print("NO")
-풀이설명
경우의 수는 두가지다. 첫 번째는 "100"으로 시작할 때, 두 번째는 "01"로 시작할 때다.
반복되는 숫자는 밑에 보이듯 n만큼 반복될 수 있다
1. 100로 시작했을때의 순서 : 01(01*n),100(0*n),1(1*n)
2. 01으로 시작했을 때의 순서100(0*n),1(1*n),01(01*n)
배운 점 : startswith라는 함수를 배웠다. 이 함수는 대소문자를 구분하고 인자값에 있는 문자열이 string에 있으면 true, 없으면 false를 반환한다.
또한, 정규표현식 re라이브러리를 이용하여 푸는 방법도 존재했다.
import sys
input = sys.stdin.readline
import re
p = re.compile('(100+1+|01)+')
for i in range(int(input())):
s = input().strip()
if p.fullmatch(s):
print("YES")
else:
print("NO")
-풀이 출처:https://velog.io/@soobin519/Python-%EB%B0%B1%EC%A4%80-1013Contact
'알고리즘' 카테고리의 다른 글
[비트마스킹/조합] 백준 1062 파이썬 (가르침) 골드4 (0) | 2022.05.30 |
---|---|
[순열/수학] 백준 1722 파이썬 (순열의 순서) 골드5 (0) | 2022.05.29 |
[그리디/정렬] 백준 1461 파이썬 (도서관) 골드5 (0) | 2022.05.27 |
[정렬,집합] 백준 1822파이썬 (차집합) 실버4 (0) | 2022.05.26 |
[다익스트라] 백준 1753파이썬 (최단경로) 골드5 (0) | 2022.05.25 |