diff --git a/Data Structures/Dynamic Programming/longestpalindromicsubstring.py b/Data Structures/Dynamic Programming/longestpalindromicsubstring.py new file mode 100644 index 00000000..e48b1c82 --- /dev/null +++ b/Data Structures/Dynamic Programming/longestpalindromicsubstring.py @@ -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] diff --git a/Leetcode/Python/Longest_Common_Subsequence.py b/Leetcode/Python/Longest_Common_Subsequence.py new file mode 100644 index 00000000..fd1e2241 --- /dev/null +++ b/Leetcode/Python/Longest_Common_Subsequence.py @@ -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]