Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 155f505

Browse files
committed
# 1143 最长公共子序列
1 parent 7247b13 commit 155f505

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

main/src/dynamic_programming/LC_1143_LongestCommonSubsequence.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,4 +85,32 @@ public int longestCommonSubsequence3(String text1, String text2) {
8585
}
8686
return dp[t1.length][t2.length];
8787
}
88+
89+
/**
90+
* 思路:
91+
* 1. 最优子结构: opt[n] = best_if(opt[n-1], opt[n-2],...)
92+
* 2. 储存中间状态:opt[i]
93+
* 3. 递推公式(状态转移方程)
94+
* Fib: opt[i] = opt[n-1] + opt[n-2]
95+
* 二维路径: opt[i][j] = fun(opt[i-1][j], opt[i][j-1])
96+
* 本题:
97+
* 需要将两个字符串转化为两个二维数组,
98+
* 用dp[][] 存储中间状态
99+
* dp方程:t1[i] == t2[j] ? opt[i][j] = opt[i-1][j-1] + 1 : opt[i][j] = opt[i-1][j] + opt[i][j-1]
100+
*/
101+
public int longestCommonSubsequence4(String text1, String text2) {
102+
char[] t1 = text1.toCharArray();
103+
char[] t2 = text2.toCharArray();
104+
int[][] dp = new int[t1.length + 1][t2.length + 1];
105+
for (int i = 1; i <= t1.length; i++) {
106+
for (int j = 1; j <= t2.length; j++) {
107+
if (t1[i - 1] == t2[j - 1]) {
108+
dp[i][j] = dp[i - 1][j - 1] + 1;
109+
} else {
110+
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
111+
}
112+
}
113+
}
114+
return dp[t1.length][t2.length];
115+
}
88116
}

main/test/dynamic_programming/LC_1143_LongestCommonSubsequenceTest.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,9 @@ public void testLongestCommonSubsequence3() {
2929
assertThat(lcs.longestCommonSubsequence3("abcde", "ace"), is(3));
3030
}
3131

32+
@Test
33+
public void testLongestCommonSubsequence4() {
34+
assertThat(lcs.longestCommonSubsequence4("abcde", "ace"), is(3));
35+
}
36+
3237
}

0 commit comments

Comments
 (0)