🔍 programmers 가장 긴 펠린드롬 - Level3
- 첫 번째 풀이
def solution(s): result = 0 def palin(index): temp = 1 left, right = index-1, index+1 if left < 0 or right >= len(s): return temp while s[left] == s[right]: left -= 1 right += 1 temp += 2 if left < 0 or right >= len(s): return temp return temp for i in range(len(s)): result = max(result, palin(i)) if result == len(s): return result return result
4개정도가 안되어서 왜 안되나 계속 고민했다
알고보니 짝수 그러니까 가운데를 끼고 펠린드롬 구하는 함수만 있어 틀렸었다.
짝수 펠린드롬도 추가해주면 정답이다.
- 풀이
def solution(s): result = 0 def palin(left, right): temp = 1 while left >= 0 and right < len(s) and s[left] == s[right]: left -= 1 right += 1 temp += 2 return temp def palin2(left, right): temp = 0 while left >= 0 and right < len(s) and s[left] == s[right]: left -= 1 right += 1 temp += 2 return temp for i in range(len(s)): result = max(result, palin(i-1, i+1), palin2(i, i+1)) if result == len(s): return result return result
palin 1은 홀수 일때고 palin 2는 짝수 일때이다.
함수를 하나로 합칠수도 있다.
- 최종 풀이
def solution(s): result = 0 def palin(left, right): while left >= 0 and right < len(s) and s[left] == s[right]: left -= 1 right += 1 return right - left - 1 for i in range(len(s)): result = max(result, palin(i-1, i+1), palin(i-1, i)) if result == len(s): return result return result
투 포인터 방법으로 풀었다.
펠린드롬 문제는 유명해서 전에 풀어봤던 기억이 있어 투포인터로 기억을 더듬어 풀었다.