Problem
Given a string, find length of the longest repeating subsequence such that the two subsequence don’t have same string character at same position, i.e., any ith character in the two subsequences shouldn’t have the same index in the original string.
Example
str = abc, return 0, There is no repeating subsequence
str = aab, return 1, The two subsequence are a(first) and a(second).
Note that b cannot be considered as part of subsequence as it would be at same index in both.
str = aabb, return 2
Solution
用二维数组进行动态规划,作为第i位和的j位已有的重复子序列长度最大值计数器。
public class Solution {
/*
* @param str: a string
* @return: the length of the longest repeating subsequence
*/
public int longestRepeatingSubsequence(String str) {
int n = str.length();
int[][] dp = new int[n+1][n+1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (i != j && str.charAt(i-1) == str.charAt(j-1)) {
dp[i][j] = dp[i-1][j-1] + 1;
} else {
dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
}
}
}
return dp[n][n];
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。