版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35508033/article/details/89069998
最长公共子串
//最长公共子串(要求连续)
//对于两个字符串,请设计一个时间复杂度为O(m*n)的算法(这里的m和n为两串的长度),求出两串的最长公共子串的长度
//给定两个字符串A和B,同时给定两串的长度n和m
动态规划:状态转移方程:
public class LongestSubstring {
public int findLongest(String A, int n, String B, int m) {
int[][] arr = new int[n + 1][m + 1];
int max = 0;
for (int i = 1; i < n + 1; i++) {
for (int j = 1; j < m + 1; j++) {
if (A.charAt(i - 1) == B.charAt(j - 1)) {
arr[i][j] = arr[i - 1][j - 1] + 1;
max = Math.max(max, arr[i][j]);
} else {
arr[i][j] = 0;
}
}
}
return max;
}
}
最长公共子序列
//最长公共子序列(不一定连续)
//给定两个字符串A和B,同时给定两个串的长度n和m,请返回最长公共子序列的长度
直接用动态规划解决,转移方程为:
public class LCS {
public int findLCS(String A, int n, String B, int m) {
int[][] arr = new int[n + 1][m + 1];
for (int i = 1; i < n + 1; i++) {
for (int j = 1; j < m + 1; j++) {
if (A.charAt(i - 1) == B.charAt(j - 1)) {
arr[i][j] = arr[i - 1][j - 1] + 1;
} else {
arr[i][j] = Math.max(arr[i][j - 1], arr[i - 1][j]);
}
}
}
return arr[n][m];
}
}