Skip to content

Commit 4e44a92

Browse files
committed
add dynamic programming longest-palindrome-substring
1 parent 9a8d82d commit 4e44a92

1 file changed

Lines changed: 84 additions & 0 deletions

File tree

‎DynamicProgramming/lps.py‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
#!/usr/bin/env python
2+
# encoding: utf-8
3+
#
4+
# Copyright (c) 2020 Vladimir Shurygin. All rights reserved.
5+
#
6+
'''
7+
Longest Palindromic Substring
8+
9+
Solution:
10+
The time complexity can be reduced by storing results of subproblems.
11+
We maintain a boolean table[n][n] that is filled in bottom up manner.
12+
The value of table[i][j] is true, if the substring is palindrome, otherwise false. To calculate table[i][j], we first check the value of table[i+1][j-1], if the value is true and str[i] is same as str[j], then we make table[i][j] true. Otherwise, the value of table[i][j] is made false.
13+
https://www.geeksforgeeks.org/longest-palindrome-substring-set-1/
14+
15+
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
16+
17+
Example 1:
18+
19+
Input: "babad"
20+
Output: "bab"
21+
Note: "aba" is also a valid answer.
22+
Example 2:
23+
24+
Input: "cbbd"
25+
Output: "bb"
26+
'''
27+
28+
29+
def longestPalSubstr(st: str) -> str:
30+
n = len(st) # get length of input string
31+
32+
# table[i][j] will be false if substring
33+
# str[i..j] is not palindrome. Else
34+
# table[i][j] will be true
35+
table = [[0 for x in range(n)] for y
36+
in range(n)]
37+
38+
# All substrings of length 1 are
39+
# palindromes
40+
max_length = 1
41+
i = 0
42+
while i < n:
43+
table[i][i] = True
44+
i = i + 1
45+
46+
# check for sub-string of length 2.
47+
start = 0
48+
i = 0
49+
while i < n - 1:
50+
if st[i] == st[i + 1]:
51+
table[i][i + 1] = True
52+
start = i
53+
max_length = 2
54+
i = i + 1
55+
56+
# Check for lengths greater than 2.
57+
# k is length of substring
58+
k = 3
59+
while k <= n:
60+
# Fix the starting index
61+
i = 0
62+
while i < (n - k + 1):
63+
# Get the ending index of
64+
# substring from starting
65+
# index i and length k
66+
j = i + k - 1
67+
68+
# checking for sub-string from
69+
# ith index to jth index iff
70+
# st[i+1] to st[(j-1)] is a
71+
# palindrome
72+
if table[i + 1][j - 1] and st[i] == st[j]:
73+
table[i][j] = True
74+
if k > max_length:
75+
start = i
76+
max_length = k
77+
i = i + 1
78+
k = k + 1
79+
return st[start: start + max_length]
80+
81+
82+
if __name__ == '__main__':
83+
actual = longestPalSubstr('babad')
84+
print(f'expected=bab; actual={actual}')

0 commit comments

Comments
 (0)