-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathLongest Palindromic Substring.py
More file actions
40 lines (30 loc) · 1006 Bytes
/
Longest Palindromic Substring.py
File metadata and controls
40 lines (30 loc) · 1006 Bytes
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
28
29
30
31
32
33
34
35
36
37
38
39
40
"""
Longest Palindromic Substring
Write a function that,given a string returns its longest palindromic substring.
A palindrome is defined as a string thats written the same forward and backward.Note
that single-character strings are palindromes.
You can assume that there will only be one longest palindromic substring.
Sample Input
string = "abaxyzzyxf"
Sample Output
"xyzzyz"
"""
# SOLUTION 1
# O(n^3) time | O(n) space
def longestPalindromicSubstring(string):
longest = ''
for i in range(len(string)):
for j in range(i, len(string)):
substring = string[i: j + 1]
if len(substring) > len(longest) and isPalindrome(substring):
longest = substring
return longest
def isPalindrome(string):
left = 0
right = len(string) - 1
while left < right:
if string[left] != string[right]:
return False
left += 1
right -= 1
return True