링크: https://www.acmicpc.net/problem/17609
유형: 문자열
, 투포인터
난이도: 골드5
스스로 풀었는가? ❌ (질문 게시판 이용)
import sys
def check_palindrome(input_str):
start_idx = 0
end_idx = len(input_str) - 1
is_pseudo_palindrome = False
while start_idx < end_idx:
if input_str[start_idx] == input_str[end_idx]:
start_idx += 1
end_idx -= 1
continue
if is_pseudo_palindrome:
return 2
if input_str[start_idx + 1] == input_str[end_idx] and input_str[start_idx] == input_str[end_idx - 1]:
tmp_start = start_idx + 1
tmp_end = end_idx
is_tmp_pseudo_palindrome = False
while tmp_start < tmp_end:
if input_str[tmp_start] == input_str[tmp_end]:
tmp_start += 1
tmp_end -= 1
continue
is_tmp_pseudo_palindrome = True
break
if not is_tmp_pseudo_palindrome:
return 1
tmp_start = start_idx
tmp_end = end_idx - 1
is_tmp_pseudo_palindrome = False
while tmp_start < tmp_end:
if input_str[tmp_start] == input_str[tmp_end]:
tmp_start += 1
tmp_end -= 1
continue
is_tmp_pseudo_palindrome = True
break
if not is_tmp_pseudo_palindrome:
return 1
return 2
if input_str[start_idx + 1] == input_str[end_idx]:
start_idx += 1
is_pseudo_palindrome = True
continue
if input_str[start_idx] == input_str[end_idx - 1]:
is_pseudo_palindrome = True
end_idx -= 1
continue
return 2
if is_pseudo_palindrome:
return 1
return 0
readline = sys.stdin.readline
T = int(readline())
input_strs = []
for i in range(T):
input_strs.append(readline().rstrip('\n'))
for input_str in input_strs:
print(check_palindrome(input_str))
is_pseudo_palindrome == True
), 2를 반환한다.is_pseudo_palindrome
의 값을 True
로 변경한다.ababbabaa
같은 케이스) 처음부터 설계 과정에서 여러 케이스를 떠올리며 로직을 설계하는 연습을 해야겠다. import sys
def is_palindrome(s, left, right):
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
def check_palindrome_or_not(input_str):
start_idx = 0
end_idx = len(input_str) - 1
while start_idx < end_idx:
if input_str[start_idx] == input_str[end_idx]:
start_idx += 1
end_idx -= 1
continue
# 두 경우 중에 하나라도 회문이면 유사 회문
if is_palindrome(input_str, start_idx + 1, end_idx) or is_palindrome(input_str, start_idx, end_idx - 1):
return 1
return 2
return 0
readline = sys.stdin.readline
T = int(readline())
input_strs = []
for i in range(T):
input_strs.append(readline().rstrip('\n'))
for input_str in input_strs:
print(check_palindrome_or_not(input_str))
[ktb-algorithm-study] 1주차