Problem: 1143. 最长公共子序列
文章目录
思路
Code
⏰ 时间复杂度: O ( n m ) O(nm) O(nm)
🌎 空间复杂度: O ( n m ) O(nm) O(nm)
Java
class Solution {
public int longestCommonSubsequence(String s1, String s2)
{
int n = s1.length();
int m = s2.length();
char[] ss1 = (" " + s1).toCharArray();
char[] ss2 = (" " + s2).toCharArray();
int[][] f = new int[n + 1][m + 1];
for (int i = 0; i <= n; i++)
Arrays.fill(f[i], 1);//有了第一个空格,任何位置的公共子序列长度都是 1
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
if (ss1[i] == ss2[j])
f[i][j] = f[i - 1][j - 1] + 1;
else
f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]);
// 减去最开始追加的空格
return f[n][m] - 1;
}
}