From 1a63777d935547b03e76586b307501f969295c23 Mon Sep 17 00:00:00 2001 From: Garvit Sharma <62982058+Imgladaitor@users.noreply.github.com> Date: Thu, 7 Oct 2021 14:44:21 +0530 Subject: [PATCH 1/2] Create longestpalindromicsubstring.py --- .../longestpalindromicsubstring.py | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Data Structures/Dynamic Programming/longestpalindromicsubstring.py 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] From 6e0ce70c45aeae34afdff3b488c51ac1d4519eaf Mon Sep 17 00:00:00 2001 From: Garvit Sharma <62982058+Imgladaitor@users.noreply.github.com> Date: Sat, 16 Oct 2021 14:09:28 +0530 Subject: [PATCH 2/2] Longest_Common_Subsequence --- Leetcode/Python/Longest_Common_Subsequence.py | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Leetcode/Python/Longest_Common_Subsequence.py 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]