From e439e544d048f62c830d6c317769eefeda86cd0b Mon Sep 17 00:00:00 2001 From: ssaumyaa7 <64359826+ssaumyaa7@users.noreply.github.com> Date: Tue, 25 May 2021 20:47:49 +0530 Subject: [PATCH] chore(Python): longest common subsequence (#322) --- algorithms/Python/README.md | 1 + .../strings/longest_common_subsequence.py | 20 +++++++++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 algorithms/Python/strings/longest_common_subsequence.py diff --git a/algorithms/Python/README.md b/algorithms/Python/README.md index 6c6b9a97..42bc1502 100644 --- a/algorithms/Python/README.md +++ b/algorithms/Python/README.md @@ -36,3 +36,4 @@ 3. [Word Count](strings/word_count.py) 4. [Remove Duplicates from a String](strings/remove_duplicates_from_a_string.py) 5. [First Non Repeating Character](strings/first_non_repeating_character.py) +6. [Longest Common Subsequence](strings/longest_common_subsequence.py) diff --git a/algorithms/Python/strings/longest_common_subsequence.py b/algorithms/Python/strings/longest_common_subsequence.py new file mode 100644 index 00000000..67730718 --- /dev/null +++ b/algorithms/Python/strings/longest_common_subsequence.py @@ -0,0 +1,20 @@ +class Solution: + def longest_common_subsequence(self, text1: str, text2: str) -> int: + n,m = len(text1),len(text2) + + grid=[[0] * (m+1) for z in range(n+1)] + + for i in range(n): + for j in range(m): + + if text1[i]==text2[j]: + grid[i+1][j+1]=grid[i][j] +1 + + else: + grid[i+1][j+1]=max(grid[i][j+1], grid[i+1][j]) + + return grid[-1][-1] + +if __name__=='__main__': + instance = Solution() + print(instance.longest_common_subsequence("abcdefg","aceg"))