Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def shortestCommonSupersequence(self, str1: str, str2: str) -> str:
- memo = {}
- def solve(i, j):
- # Base Case: If one string is empty, return the rest of the other string
- if i == len(str1): return str2[j:]
- if j == len(str2): return str1[i:]
- # Check memoization table
- if (i, j) in memo:
- return memo[(i, j)]
- # If characters match, I take it once and move forward in both
- if str1[i] == str2[j]:
- res = str1[i] + solve(i + 1, j + 1)
- else:
- # Option 1: Take character from str1
- option1 = str1[i] + solve(i + 1, j)
- # Option 2: Take character from str2
- option2 = str2[j] + solve(i, j + 1)
- # Pick the shorter result
- if len(option1) < len(option2):
- res = option1
- else:
- res = option2
- memo[(i, j)] = res
- return res
- return solve(0, 0)
Advertisement
Add Comment
Please, Sign In to add comment