본문 바로가기
알고리즘/[python] 백준 BOJ

[python] 백준 17609 회문

by Alan_Kim 2023. 4. 23.
728x90
반응형

https://www.acmicpc.net/problem/17609

 

17609번: 회문

각 문자열이 회문인지, 유사 회문인지, 둘 모두 해당되지 않는지를 판단하여 회문이면 0, 유사 회문이면 1, 둘 모두 아니면 2를 순서대로 한 줄에 하나씩 출력한다.

www.acmicpc.net

 

문제 해결

  • 양쪽 끝 start = 0 , end = len(word)-1로 시직해서 투포인터로 양쪽 대칭을 확인하는 문제
  • 만약 대칭이 안되는 부분이 있다면 양쪽 중 한 문자를 없앴을 때 대칭이 되는지 확인
  • 주의할 점은 대칭이 안되는 부분이 abca와 같이 붙어있는 경우가 있으므로 start<=end-1 혹은 start+1<=end 둘 중 하나를 생각해서 aba 또는 aca로 유사 회문인 것을 확인해야한다.(이부분을 찾지 못했는데 질문게시판을 통해 알 수 있었다.)

 

CODE

import sys
input = sys.stdin.readline

def check(word):
    start = 0
    end = len(word)-1
    while start < end:
        if word[start] == word[end]:
            start += 1
            end -=1
        else:
            if start <= end-1:
                temp = word[:end] + word[end+1:]
                if temp[:] == temp[::-1]:
                    return 1
            if start +1 < end:
                temp = word[:start] + word[start+1:]
                if temp[:] == temp[::-1]:
                    return 1
            return 2
    return 0
if __name__=='__main__':
    t = int(input())
    for _ in range(t):
        string = str(input().rstrip())
        print(check(string))
728x90
반응형

댓글