标签:image col pre bar ble sub img turn ref
这道题类似最长公共子序列,可以使用动态规划来解决。
二维的
/**
* 1 <= len(A), len(B) <= 1000
* 0 <= A[i], B[i] < 100
*/
class Solution {
public int findLength(int[] A, int[] B) {
int row = A.length;
int col = B.length;
int[][] dp = new int[row + 1][col + 1];
int res = 0;
for(int i = 1; i <= row; i++){
for(int j = 1; j <= col; j++){
if(A[i - 1] == B[j - 1]){
dp[i][j] = dp[i - 1][j - 1] + 1;
if(res < dp[i][j]){
res = dp[i][j];
}
}
else{
dp[i][j] = 0;
}
}
}
return res;
}
}
一维的
/**
* 1 <= len(A), len(B) <= 1000
* 0 <= A[i], B[i] < 100
*/
class Solution {
public int findLength(int[] A, int[] B) {
int row = A.length;
int col = B.length;
int[] dp = new int[col + 1];
int res = 0;
for(int i = 1; i <= row; i++){
//从后向前遍历,防止dp[j-1]的值被冲掉
for(int j = col; j >= 1; j--){
if(A[i - 1] == B[j - 1]){
dp[j] = dp[j - 1] + 1;
}
else{
dp[j] = 0;
}
res = Math.max(res, dp[j]);
}
}
return res;
}
}
标签:image col pre bar ble sub img turn ref
原文地址:https://www.cnblogs.com/realzhaijiayu/p/13222185.html