Skip to content

Commit 98081d9

Browse files
committed
addition of longest palindrome substring
1 parent 3cc9e6a commit 98081d9

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

longest_palindrome.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Given a string s, return the longest palindromic substring in s.
2+
# Constraints: 1 <= s.length <= 1000
3+
# s consist of only digits and English letters (lower-case and/or upper-case)
4+
5+
class Solution:
6+
def longestPalindrome(self, s: str) -> str:
7+
vel = [[False for i in range(len(s))] for i in range(len(s))]
8+
for i in range(len(s)):
9+
vel[i][i] = True
10+
max_len = 1
11+
start = 0
12+
for k in range (2, len(s)+1):
13+
for i in range (len(s)-k+1):
14+
end = i + k
15+
if k == 2:
16+
if s[i] == s[end-1]:
17+
vel[i][end-1]=True
18+
max_len = k
19+
start = i
20+
else:
21+
if s[i] == s[end-1] and vel[i+1][end-2]:
22+
vel[i][end-1]=True
23+
max_len = k
24+
start = i
25+
return s[start:start+max_len]
26+
27+
# How I solved it
28+
# Define one square matrix of order same as the length of string, and fill it with False
29+
# Set the major diagonal elements as true, so Vel[i, i] = True for all i from 0 to order – 1
30+
# start := 0
31+
# for k in range 2 to length of S + 1
32+
# for i in range 0 to length of S – k + 1
33+
# end := i + k
34+
# if k = 2, then
35+
# if S[i] = S[end - 1], then
36+
# vel[i, end - 1] = True, max_len := k, and start := i
37+
# otherwise
38+
# if S[i] = S[end - 1] and vel[i + 1, end - 2], then
39+
# vel[i, end - 1] = True, max_len := k, and start := i
40+
# return a substring of from index start to start + max_len

0 commit comments

Comments
 (0)