Skip to content

Commit 694e61b

Browse files
authored
Merge pull request #55 from krishnak3101/leet_code_que_5
Leet code que no 5
2 parents 7b8453f + 91c9bca commit 694e61b

2 files changed

Lines changed: 83 additions & 0 deletions

File tree

0005/README.MD

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
## Longest Palindromic substring
2+
3+
4+
Find the longest palindromic substring in a given string S
5+
* Ex1 :
6+
For S = cadab, answer is ada
7+
8+
* Ex2 : For S = cadac, answer is cadac
9+
10+
Link to the problem :- https://leetcode.com/problems/longest-palindromic-substring/
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
class Solution:
2+
def longestPalindrome(self, s: str) -> str:
3+
# Two pointer approach , time complexity O(n), space complexity O(1)
4+
max_len = -float("inf")
5+
max_ind = [-1, -1]
6+
7+
# odd lenth palindromes
8+
for k in range(len(s)):
9+
i = k
10+
j = k
11+
while(i >= 0 and j <= len(s) - 1):
12+
if s[i] == s[j]:
13+
if (j - i + 1) > max_len:
14+
max_len = j - i + 1
15+
max_ind = [i, j]
16+
17+
i -= 1
18+
j += 1
19+
20+
else:
21+
break
22+
23+
# even lenth palindromes
24+
for k in range(len(s) - 1):
25+
i = k
26+
j = k + 1
27+
while(i >= 0 and j <= len(s) - 1):
28+
if s[i] == s[j]:
29+
if (j - i + 1) > max_len:
30+
max_len = j - i + 1
31+
max_ind = [i, j]
32+
33+
i -= 1
34+
j += 1
35+
36+
else:
37+
break
38+
39+
return s[max_ind[0]:max_ind[1] + 1]
40+
41+
# Dynamic Programming approach ,
42+
# Time complexity O(n^2), Space complexity O(n^2)
43+
44+
dp = [[0 for _ in range(len(s))] for _ in range(len(s))]
45+
46+
# sub string of length 1
47+
for i in range(len(s)):
48+
dp[i][i] = 1
49+
50+
# substring of length 1 id always a palindrome
51+
max_len = 1
52+
max_ind = [0, 0]
53+
54+
# sub string of length 2
55+
for i in range(len(s) - 1):
56+
if s[i] == s[i + 1]:
57+
dp[i][i + 1] = 1
58+
if max_len == 1:
59+
max_len = 2
60+
max_ind[0] = i
61+
max_ind[1] = i + 1
62+
63+
# sub string of length greater than 2
64+
for j in range(2, len(s)):
65+
for i in range(0, len(s) - j):
66+
k = j + i
67+
if (s[k] == s[i]) and (dp[i + 1][k - 1] == 1):
68+
dp[i][k] = 1
69+
if (k - i + 1) > max_len:
70+
max_len = k - i + 1
71+
max_ind = [i, k]
72+
73+
return s[max_ind[0]:max_ind[1] + 1]

0 commit comments

Comments
 (0)