Skip to content

Commit

Permalink
Add java code for LCS
Browse files Browse the repository at this point in the history
  • Loading branch information
Shawn-Hx authored and labuladong committed Nov 12, 2020
1 parent 6294fbc commit 4591b79
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion 动态规划系列/最长公共子序列.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,4 +147,29 @@ else:
<img src="../pictures/qrcode.jpg" width=200 >
</p>

======其他语言代码======
======其他语言代码======

[Shawn](https://github.com/Shawn-Hx) 提供 Java 代码:

```java
public int longestCommonSubsequence(String text1, String text2) {
// 字符串转为char数组以加快访问速度
char[] str1 = text1.toCharArray();
char[] str2 = text2.toCharArray();

int m = str1.length, n = str2.length;
// 构建dp table,初始值默认为0
int[][] dp = new int[m + 1][n + 1];
// 状态转移
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
if (str1[i - 1] == str2[j - 1])
// 找到LCS中的字符
dp[i][j] = dp[i-1][j-1] + 1;
else
dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);

return dp[m][n];
}
```

0 comments on commit 4591b79

Please sign in to comment.