Problem
While solving the Longest Repeating Subsequence problem using bottom-up dynamic programming, I started running into an edge case whenever a letter was repeated an odd number of times.
Minimum Reproducible Example
s = 'AXXXA'
n = len(s)
dp = [['' for i in range(n + 1)] for j in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, n + 1):
if (i != j and s[i - 1] == s[j - 1]):
dp[i][j] = dp[i - 1][j - 1] + s[i - 1]
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
print(dp[n][n])
Question
Any pointers on how to avoid this?
With input s = ‘AXXXA’, the answer should be either A or X, but the final result returns XX, apparently pairing up the third X with both the first X and the second X.