Skip to content

Commit a3dbe49

Browse files
committed
Added the Longest Palindromic Substring Solution
1 parent afba8e2 commit a3dbe49

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
'''
2+
Problem:-
3+
4+
Given a string s, find the longest palindromic substring in s.
5+
You may assume that the maximum length of s is 1000.
6+
7+
Example 1:
8+
Input: "babad"
9+
Output: "bab"
10+
Note: "aba" is also a valid answer.
11+
12+
'''
13+
14+
class Solution:
15+
def longestPalindrome(self, s: str) -> str:
16+
res = ""
17+
resLen = 0
18+
19+
for i in range(len(s)):
20+
# odd length
21+
l, r = i, i
22+
while l >= 0 and r < len(s) and s[l] == s[r]:
23+
if (r - l + 1) > resLen:
24+
res = s[l:r + 1]
25+
resLen = r - l + 1
26+
l -= 1
27+
r += 1
28+
29+
# even length
30+
l, r = i, i + 1
31+
while l >= 0 and r < len(s) and s[l] == s[r]:
32+
if (r - l + 1) > resLen:
33+
res = s[l:r + 1]
34+
resLen = r - l + 1
35+
l -= 1
36+
r += 1
37+
38+
return res

0 commit comments

Comments
 (0)