728x90
https://school.programmers.co.kr/learn/courses/30/lessons/12904
풀이
1. 2중 for문 완전 탐색
Time: 3926.56 ms
def solution(s):
answer = 0
for i in range(len(s)):
for j in range(i+1,len(s)+1):
if s[i:j]==s[i:j][::-1]:
answer=max(answer, len(s[i:j]))
return answer
"abacde"
a
ab
aba
abac
abacd
abacde
b
ba
bac
bacd
bacde
a
ac
acd
acde
c
cd
cde
d
de
e
2. 투포인터 홀수, 짝수 길이 나눠서
Time: 238.34 ms
def solution(s):
answer = 0
if s == s[::-1]:
return len(s)
def pail(i, j):
while i >= 0 and j < len(s) and s[i] == s[j]:
i -= 1
j += 1
return len(s[i+1:j])
for i in range(len(s)):
answer = max(answer, pail(i, i+1), pail(i, i+2))
return answer
"abacde"
ab
aba
ba
a
ac
c
cd
d
de
e
3. 2중 for문 투포인터
Time: 0.85 ms
def solution(s):
answer = 0
for i in range(len(s)):
for j in range(len(s), i, -1):
if j - i < answer:
break
if s[i:j] == s[i:j][::-1]:
answer=j-i
break
return answer
"abacde"
abacde
abacd
abac
aba
bacde
bacd
bac
acde
acd
cde
4. 문자열 길이 긴 것부터 시작 인덱스 나눠서
Time: 0.01 ms
def solution(s):
for i in range(len(s),0,-1): # 문자열 길이 긴 것 부터
for j in range(len(s)-i+1): # 문자열 시작 인덱스
if s[j:j+i] == s[j:j+i][::-1]:
return i
"abacde"
abacde
abacd
bacde
abac
bacd
acde
aba
728x90