算法:最长子序列1143. Longest Common Subsequence
Posted 架构师易筋
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法:最长子序列1143. Longest Common Subsequence相关的知识,希望对你有一定的参考价值。
# 1143. Longest Common Subsequence
Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
For example, “ace” is a subsequence of “abcde”.
A common subsequence of two strings is a subsequence that is common to both strings.
Example 1:
Input: text1 = "abcde", text2 = "ace"
Output: 3
Explanation: The longest common subsequence is "ace" and its length is 3.
Example 2:
Input: text1 = "abc", text2 = "abc"
Output: 3
Explanation: The longest common subsequence is "abc" and its length is 3.
Example 3:
Input: text1 = "abc", text2 = "def"
Output: 0
Explanation: There is no such common subsequence, so the result is 0.
Constraints:
1 <= text1.length, text2.length <= 1000
text1 and text2 consist of only lowercase English characters.
解法:升级为二维表格,动态规划解决
- | a(1) | c(2) | e(3) |
---|---|---|---|
a(1) | 1 (1, 1) | 1 (1, 2) | 1 |
b(2) | 1 (2, 1) | 1 | 1 |
c(3) | 1 | 2 | 2 |
d(4) | 1 | 2 | 2 |
e (5) | 1 | 2 | 3 |
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int rowLen = text1.length();
int colLen = text2.length();
char[] chars1 = text1.toCharArray();
char[] chars2 = text2.toCharArray();
int[][] dp = new int[rowLen + 1][colLen + 1];
for (int r = 0; r < rowLen; r++) {
for (int c = 0; c < colLen; c++) {
if (chars1[r] == chars2[c]) {
dp[r + 1][c + 1] = 1 + dp[r][c];
} else {
dp[r + 1][c + 1] = Math.max(dp[r + 1][c], dp[r][c + 1]);
}
}
}
return dp[rowLen][colLen];
}
}
以上是关于算法:最长子序列1143. Longest Common Subsequence的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 1143. Longest Commom Subsequence 最长公共子序列(中等)
算法: 最长公共子串1143. Longest Common Subsequence