Skip to content

Commit 99f1eef

Browse files
committed
O(n^2) time and O(n) space using DP
1 parent 77adb47 commit 99f1eef

File tree

1 file changed

+26
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)