Skip to content

Create longestpalindromicsubstring.py #360

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions Data Structures/Dynamic Programming/longestpalindromicsubstring.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Problem Statement link:- https://leetcode.com/problems/longest-palindromic-substring/

def longestPalindrome(self, s: str) -> str:

n=len(s)
dp=[]
for _ in range(n):
dp.append([None]*n)

maxLen=1
start,end=0,0 #start,end

for i in range(n):
dp[i][i]=1 #main diag

if i+1<=n-1:#2nd diag
if s[i]==s[i+1]:
dp[i][i+1]=2
maxLen=2
start,end=i,i+1 #start,end
else:
dp[i][i+1]=0



for d in range(2,n): #2,3,4,..,n
for rStart in range(n):
cEnd=d+rStart
if cEnd>n-1: break

if s[rStart]==s[cEnd] and dp[rStart+1][cEnd-1]>0:
dp[rStart][cEnd]=dp[rStart+1][cEnd-1]+2

#update the longest palindromic substring
if (cEnd-rStart+1)>maxLen:
maxLen=(cEnd-rStart+1)
start,end=rStart,cEnd

else:dp[rStart][cEnd]=0

return s[start:end+1]
22 changes: 22 additions & 0 deletions Leetcode/Python/Longest_Common_Subsequence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Problem Description:- Longest_Common_Subsequence
#Link:- https://leetcode.com/problems/longest-common-subsequence/


class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:

m = len(text2)
n = len(text1)

memo = [[0 for j in range(m+1)] for i in range(n+1)]

for i in range(n-1,-1,-1):
for j in range(m-1,-1,-1):

if text1[i] == text2[j]:
memo[i][j] = 1 + memo[i+1][j+1]

else:
memo[i][j] = max(memo[i+1][j],memo[i][j+1])

return memo[0][0]