File tree 1 file changed +28
-0
lines changed
1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change @@ -164,6 +164,34 @@ public:
164
164
}
165
165
};
166
166
```
167
+
168
+ [weijiew](https://github.com/weijiew) 提供Java解法代码:
169
+
170
+ ```java
171
+ class Solution {
172
+ public int longestCommonSubsequence(String text1, String text2) {
173
+ int m = text1.length(), n = text2.length();
174
+ // 构建 DP table 和 base case
175
+ // dp[i][j] 表示: 字符串 str1[0:i] 和字符串 str2[0:j] 的最大公共子序列
176
+ int[][] dp = new int[m+1][n+1];
177
+ // 进行状态转移
178
+ for(int i = 1; i <= m; i++){
179
+ for(int j = 1; j <= n; j++){
180
+ if(text1.charAt(i-1) == text2.charAt(j-1)){ // 若两个字符相等,必然可以构成子问题的最优解
181
+ // 这个字符存在于 lcs 之中
182
+ dp[i][j] = dp[i-1][j-1] + 1;
183
+ }else{
184
+ // 此时 text1[i] != text2[j] 则表示至少有一个不在 lcs 中(要么 text1[i] 不在,要么 text2[j]不在,或者都不在)。
185
+ // 所以当前结果就相当于之前结果的中最大的那一个
186
+ dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);
187
+ }
188
+ }
189
+ }
190
+ return dp[m][n];
191
+ }
192
+ }
193
+ ```
194
+
167
195
[上一篇:动态规划之正则表达](../动态规划系列/动态规划之正则表达.md)
168
196
169
197
[下一篇:学习算法和刷题的思路指南](../算法思维系列/学习数据结构和算法的高效方法.md)
You can’t perform that action at this time.
0 commit comments