• + 0 comments

    python:

    def commonChild(s1, s2):
        # init a DP table with dimensions (len(s1)+1) x (len(s2)+1)
        dp = [[0] * (len(s2) + 1) for _ in range(len(s1) + 1)]
        # filling the DP table
        for i in range(1, len(s1) + 1):
            for j in range(1, len(s2) + 1):
                if s1[i - 1] == s2[j - 1]:
                    # match found
                    dp[i][j] = dp[i - 1][j - 1] + 1
                else:
                    # taking max from previous states
                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])  
        # at the right-bottom of BP there is the value we want
        return dp[len(s1)][len(s2)]