Recently Updated
RacecaR
Challenge
Aren’t Palindromes cool? I certainly think so, which is why I want you to find the longest palindrome in this file.
Solution
This is the longest palindrome substring problem
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def longestPalindrome(s):
l = len(s)
if l <= 2:
if (s[0] != s[l-1]): return ''
else: return s
result = ''
for i in range(0,l):
palindrome = SearchPalindrome(s, i, i)
if len(palindrome) > len(result): result = palindrome
palindrome = SearchPalindrome(s, i, i+1)
if len(palindrome) > len(result): result = palindrome
return result
def SearchPalindrome(string, start, end):
while(start>=0 and end < len(string) and string[start]==string[end]):
start -= 1
end += 1
return string[start+1:end]
text = ''
with open('palindrome.txt') as f:
for line in f:
text += line.rstrip()
print longestPalindrome(text)
output
1
DbrMrbD
Flag