Skip to content

Instantly share code, notes, and snippets.

@thmain
Last active April 25, 2025 21:24
Show Gist options
  • Save thmain/531b5feca3246903c8fc6d33aef59749 to your computer and use it in GitHub Desktop.
Save thmain/531b5feca3246903c8fc6d33aef59749 to your computer and use it in GitHub Desktop.
# abcde
# xabcy
# -- abcde , abcygabcdn
def lcs(word1, word2):
memo = {}
return find(word1, word2, 0, 0, 0, memo)
def find(word1, word2, i, j, count, memo):
if i == len(word1) or j == len(word2):
return count
key = (i, j, count)
if key in memo:
return memo[key]
curr_count = count
if word1[i] == word2[j]:
curr_count = find(word1, word2, i + 1, j + 1, count + 1, memo)
result = max(
curr_count,
find(word1, word2, i + 1, j, 0, memo),
find(word1, word2, i, j + 1, 0, memo)
)
memo[key] = result
return result
x = lcs("abcde", "abcygabcdn")
print(x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment