面试高频题-最长公共子序列

题目链接:1143. 最长公共子序列

最长公共子序列,英文缩写为LCS(Longest Common Subsequence)。给定两个字符串t1t2,返回两个字符串最长公共子序列,不存在最长公共子序列返回0。

字符串的子序列可以定义为:在原字符串不改变字符相对顺序的情况下删除某些字符串后形成的新的字符串。

解决方案

动态规划

上面问题的状态表示:代表考虑的前个字符,考虑的前个字符,形成的最长公共子序列长度。转移方程可以表示为:

  • 时,。
  • 时,。

实例代码为:

class Solution {
    public int longestCommonSubsequence(String t1, String text2) {
        int m = t1.length(), n = text2.length();
        int[][] dp = new int[m + 1][n + 1];
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (t1.charAt(i - 1) == text2.charAt(j - 1)) dp[i][j] = dp[i - 1][j - 1] + 1;
                else dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]);
            }
        }
        return dp[m][n];
    }
}

增加一个空行以减少边界条件的判断。

参考文献:

  1. 【面试高频题】难度 1.5/5,LCS 模板题

你可能感兴趣的:(面试高频题-最长公共子序列)