LeetCode 3316. 从原字符串里进行删除操作的最多次数(LCS问题)
原题链接
中等
作者:
autumn_0
,
2024-10-14 16:54:39
,
所有人可见
,
阅读 7
class Solution {
public int maxRemovals(String source, String pattern, int[] targetIndices) {
HashSet<Integer> set = new HashSet<>();
for(int x: targetIndices){
set.add(x + 1);
}
int n = source.length(), m = pattern.length();
int[][] f = new int[n + 1][m + 1];
for(int i = 0; i <= n; i ++ ){
Arrays.fill(f[i], Integer.MIN_VALUE);
}
f[0][0] = 0;
for(int i = 1; i <= n; i ++ ){
for(int j = 0; j <= m; j ++ ){
f[i][j] = f[i - 1][j] + (set.contains(i) ? 1 : 0);
if(j > 0 && source.charAt(i - 1) == pattern.charAt(j - 1)){
f[i][j] = Math.max(f[i][j], f[i - 1][j - 1]);
}
}
}
return f[n][m];
}
}