- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path5.py
More file actions
Latest commit
29 lines (24 loc) · 1.03 KB
/
Copy path5.py
File metadata and controls
29 lines (24 loc) · 1.03 KB
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
# Name: Longest Palindromic Substring
# Link: https://leetcode.com/problems/longest-palindromic-substring/
# Method: DP, is string from [i,j] a palindrome (alternatively, expand from middle)
# Time: O(n^2)
# Space: O(n)
# Difficulty: Medium
classSolution:
deflongestPalindrome(self, s: str) ->str:
max_pal_len=1
max_val_idx= [0, 0]
# Optimised DP using only 2 lines
is_pal_line= [Falsefor_inrange(len(s))]
is_pal_line[-1] =True
foriinrange(len(s) -1, -1, -1): # From bottom up, looking after diagonal
is_pal_now= [Falsefor_inrange(len(s))]
is_pal_now[i] =True
forjinrange(i+1, len(s)):
ifs[i] ==s[j] and (j-i==1oris_pal_prev[j-1]):
is_pal_now[j] =True
ifj-i+1>max_pal_len:
max_pal_len=j-i+1
max_val_idx= [i, j]
is_pal_prev=is_pal_now
returns[max_val_idx[0] : max_val_idx[1] +1]