chore(Python): longest common subsequence (#322)

pull/324/head
ssaumyaa7 2021-05-25 20:47:49 +05:30 committed by GitHub
parent 12138da6cb
commit e439e544d0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 0 deletions

View File

@ -36,3 +36,4 @@
3. [Word Count](strings/word_count.py) 3. [Word Count](strings/word_count.py)
4. [Remove Duplicates from a String](strings/remove_duplicates_from_a_string.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) 5. [First Non Repeating Character](strings/first_non_repeating_character.py)
6. [Longest Common Subsequence](strings/longest_common_subsequence.py)

View File

@ -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"))