Skip to content

Commit b82c77a

Browse files
authored
Merge pull request #3 from emcc2302/emcc2302-patch-2
Create Code Testcase Test Result Test Result 5. Longest Palindromic …
2 parents 557973f + 00a3b91 commit b82c77a

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
def longestPalindrome(self, s):
2+
longest_palindrom = ''
3+
dp = [[0]*len(s) for _ in range(len(s))]
4+
#filling out the diagonal by 1
5+
for i in range(len(s)):
6+
dp[i][i] = True
7+
longest_palindrom = s[i]
8+
9+
# filling the dp table
10+
for i in range(len(s)-1,-1,-1):
11+
# j starts from the i location : to only work on the upper side of the diagonal
12+
for j in range(i+1,len(s)):
13+
if s[i] == s[j]: #if the chars mathces
14+
# if len slicied sub_string is just one letter if the characters are equal, we can say they are palindomr dp[i][j] =True
15+
#if the slicied sub_string is longer than 1, then we should check if the inner string is also palindrom (check dp[i+1][j-1] is True)
16+
if j-i ==1 or dp[i+1][j-1] is True:
17+
dp[i][j] = True
18+
# we also need to keep track of the maximum palindrom sequence
19+
if len(longest_palindrom) < len(s[i:j+1]):
20+
longest_palindrom = s[i:j+1]
21+
22+
return longest_palindrom

0 commit comments

Comments
 (0)