정올/KOI기출 문제
정올 회문
juwanseo
2025. 5. 6. 21:21
string = []
n = int(input())
for _ in range(n):
string.append(input().strip())
def palindrome(s, e, temp):
while s <= e:
if str[s] == str[e]:
s += 1
e -= 1
else:
if temp == 0:
left = palindrome(s+1, e, temp+1)
right = palindrome(s, e-1, temp+1)
return min(left, right)
else:
return 2
return temp
result = []
for str in string:
s, e = 0, len(str)-1
result.append(palindrome(s, e, 0))
for r in result:
print(r)
s, e: 비교할 시작 인덱스와 끝 인덱스
string: 검사할 문자열
edit_count: 삭제 횟수. 0이면 아직 삭제 안 했음.
문자열을 앞뒤에서 비교
같으면 한 칸씩 안쪽으로 이동 (s += 1, e -= 1)
다르면:
아직 문자를 삭제한 적이 없다면:
왼쪽 문자 제거하고 다시 검사 (s+1)
오른쪽 문자 제거하고 다시 검사 (e-1)
두 경우 중 더 적은 편집으로 해결된 결과 반환
이미 한 번 삭제했는데 또 다르면 → 2 반환 (불가능)
끝까지 무사히 비교 완료 → edit_count 반환 (0 또는 1)
문자열의 개수와 각 문자열을 입력받아 리스트에 저장
각 문자열마다 is_palindrome 함수를 호출하고, 그 결과(0, 1, 2)를 출력
import sys
input = sys.stdin.readline
n = int(input())
for _ in range(n):
arr = list(input().strip())
l = len(arr)
s = 0
e = len(arr)-1
count = 0
while s<e:
if arr[s] == arr[e]:
e-=1
s+=1
else:
if arr[s:e] == arr[s:e][::-1] or arr[s+1:e+1] == arr[s+1:e+1][::-1]:
count = 1
else:
count = 2
break
print(count)