Skip to content

Commit

Permalink
【1143.最长公共子序列】【C++ 】 (labuladong#500)
Browse files Browse the repository at this point in the history
* add 1143 C++ version

* add comment

Co-authored-by: Ed <[email protected]>
Co-authored-by: labuladong <[email protected]>
  • Loading branch information
3 people authored Nov 17, 2020
1 parent 12fbf29 commit 0ad9a50
Showing 1 changed file with 36 additions and 1 deletion.
37 changes: 36 additions & 1 deletion 动态规划系列/最长公共子序列.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# 最长公共子序列
# 最长公共子序列


<p align='center'>
Expand Down Expand Up @@ -149,6 +149,40 @@ else:

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


[Edwenc](https://github.com/Edwenc) 提供 C++ 代码:

```C++
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
// 先计算两条字符串的长度
int m = text1.size();
int n = text2.size();

// 构建dp矩阵 默认初始值0
// 这里会多扩建一边和一列
// 因为dp[i][j]的含义是:对于 s1[1..i] 和 s2[1..j],它们的LCS长度是 dp[i][j]
// 所以当i或者j为零时 LCS的长度默认为0
vector< vector<int> > dp ( m+1 , vector<int> ( n+1 , 0 ) );

// 状态转移
// i、j都从1开始遍历 因为下面的操作中都会-1 相当于从0开始
for ( int i=1 ; i<m+1 ; i++ ){
for ( int j=1 ; j<n+1 ; j++ ){
// 如果text1和text2相同
// 就在它们的前一位基础上加一
// 如果不同 只能在之前的两者中去最大
dp[i][j] = (text1[i-1] == text2[j-1]) ? dp[i-1][j-1] + 1 : max( dp[i-1][j] , dp[i][j-1] );
}
}

// 返回最终右下角的值
return dp[m][n];
}
};
```

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

```java
Expand All @@ -173,3 +207,4 @@ public int longestCommonSubsequence(String text1, String text2) {
}
```


0 comments on commit 0ad9a50

Please sign in to comment.