Skip to content

Commit 4591b79

Browse files
Shawn-Hxlabuladong
authored andcommitted
Add java code for LCS
1 parent 6294fbc commit 4591b79

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

动态规划系列/最长公共子序列.md

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,4 +147,29 @@ else:
147147
<img src="../pictures/qrcode.jpg" width=200 >
148148
</p>
149149

150-
======其他语言代码======
150+
======其他语言代码======
151+
152+
[Shawn](https://github.com/Shawn-Hx) 提供 Java 代码:
153+
154+
```java
155+
public int longestCommonSubsequence(String text1, String text2) {
156+
// 字符串转为char数组以加快访问速度
157+
char[] str1 = text1.toCharArray();
158+
char[] str2 = text2.toCharArray();
159+
160+
int m = str1.length, n = str2.length;
161+
// 构建dp table,初始值默认为0
162+
int[][] dp = new int[m + 1][n + 1];
163+
// 状态转移
164+
for (int i = 1; i <= m; i++)
165+
for (int j = 1; j <= n; j++)
166+
if (str1[i - 1] == str2[j - 1])
167+
// 找到LCS中的字符
168+
dp[i][j] = dp[i-1][j-1] + 1;
169+
else
170+
dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
171+
172+
return dp[m][n];
173+
}
174+
```
175+

0 commit comments

Comments
 (0)