Skip to content

Commit a6d8743

Browse files
authored
Merge pull request prabhupant#341 from erithwik/longest-palindromic-substring
Add Longest Palindromic Substring
2 parents 0b53753 + 4974fbc commit a6d8743

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
def longest_palindromic_substring_DP(s):
2+
3+
S = [[False for i in range(len(s))] for j in range(len(s))]
4+
5+
max_palindrome = ""
6+
7+
for i in range(len(s))[::-1]:
8+
for j in range(i, len(s)):
9+
# if j - 1 < 3, then there is one or two characters between these
10+
# two positions, implying that if s[i] == s[j]
11+
# then that small string is a palindrome
12+
# We check if the above cases is valid or i
13+
# they are larger, we use DP to check the substring
14+
# in between j and i
15+
S[i][j] = s[i] == s[j] and (j - i < 3 or S[i+1][j-1])
16+
if S[i][j] and j - i + 1 > len(max_palindrome):
17+
max_palindrome = s[i:j+1]
18+
19+
return max_palindrome
20+
21+
22+
def longest_palindromic_substring_expansion(s):
23+
max_palindrome = ""
24+
25+
for i in range(len(s) * 2 - 1):
26+
if i % 2 == 0:
27+
# This is when you are "on" an actual character
28+
# o = offset, ind = current character
29+
o = 0
30+
ind = i // 2
31+
while ind + o < len(s) and ind - o >= 0:
32+
if(s[ind + o] != s[ind - o]):
33+
break
34+
if ind + o - (ind - o) + 1 > len(max_palindrome):
35+
max_palindrome = s[ind-o:ind+o + 1]
36+
o += 1
37+
else:
38+
# This is when you are "in the middle of" two characters
39+
# o = offset, sind = start char, eind = end char
40+
o = 0
41+
sind = i // 2
42+
eind = i // 2 + 1
43+
while sind - o >= 0 and eind + o < len(s):
44+
if(s[sind - o] != s[eind + o]):
45+
break
46+
if eind + o - (sind - o) + 1 > len(max_palindrome):
47+
max_palindrome = s[sind - o:eind + o + 1]
48+
o += 1
49+
50+
return max_palindrome
51+
52+
53+
input_string = "abbbacdcaacdca"
54+
55+
ans_DP = longest_palindromic_substring_DP(input_string)
56+
ans_expansion = longest_palindromic_substring_expansion(input_string)
57+
print("DP Solution: {}, Expansion Solution: {}".format(ans_DP, ans_expansion))

0 commit comments

Comments
 (0)