We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
def commonChild(s1, s2):
# Allocate memory of size ([s1] + 1) * ([s2] + 1)
# to contain the max child length starting with empty string.
dp = [[0] * (len(s2) + 1) for _ in range(len(s1) + 1)]
# Compare every pair of characters in both strings.
for i, c1 in enumerate(s1):
for j, c2 in enumerate(s2):
# If matching, add up to the score of the previous pair.
if c1 == c2:
dp[i + 1][j + 1] = dp[i][j] + 1
# Otherwise, paste the max score for two previous
# reachable pairs.
else:
dp[i + 1][j + 1] = max(dp[i + 1][j], dp[i][j + 1])
# As the max score is being brought further through iterations,
# return the score for the last pair.
return dp[-1][-1]
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Common Child
You are viewing a single comment's thread. Return to all comments →
I have added some comments to your solution: