Skip to content

Commit 49c28dc

Browse files
committed
Python solution for Longest palindromic substring
1 parent 313574a commit 49c28dc

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#https://leetcode.com/problems/longest-palindromic-substring/
2+
3+
class Solution(object):
4+
def longestPalindrome(self, s):
5+
"""
6+
:type s: str
7+
:rtype: str
8+
"""
9+
10+
# result to store palindrome
11+
res = ""
12+
13+
for i in range(len(s)):
14+
15+
# for odd len strings
16+
# Eg : "racecar"
17+
tmp = self.helper(i, i, s)
18+
if len(res) < len(tmp):
19+
res = tmp
20+
21+
# for even len strings
22+
# Eg: "aaaabbaa"
23+
tmp = self.helper(i, i + 1, s)
24+
if len(res) < len(tmp):
25+
res = tmp
26+
27+
28+
return res
29+
30+
def helper(self, l, r, s):
31+
# Helper function to check if the left pointer and right pointer are equal
32+
# if inbound and palindrome, move left left and right right
33+
34+
while (l >= 0 and r < len(s) and s[l] == s[r]):
35+
l -= 1
36+
r += 1
37+
38+
39+
return s[l + 1: r]

0 commit comments

Comments
 (0)