File tree Expand file tree Collapse file tree 1 file changed +36
-1
lines changed
Expand file tree Collapse file tree 1 file changed +36
-1
lines changed Original file line number Diff line number Diff line change 1- # 最长公共子序列
1+ # 最长公共子序列
22
33
44<p align =' center ' >
@@ -149,6 +149,40 @@ else:
149149
150150======其他语言代码======
151151
152+
153+ [ Edwenc] ( https://github.com/Edwenc ) 提供 C++ 代码:
154+
155+ ``` C++
156+ class Solution {
157+ public:
158+ int longestCommonSubsequence(string text1, string text2) {
159+ // 先计算两条字符串的长度
160+ int m = text1.size();
161+ int n = text2.size();
162+
163+ // 构建dp矩阵 默认初始值0
164+ // 这里会多扩建一边和一列
165+ // 因为dp[ i] [ j ] 的含义是:对于 s1[ 1..i] 和 s2[ 1..j] ,它们的LCS长度是 dp[ i] [ j ] 。
166+ // 所以当i或者j为零时 LCS的长度默认为0
167+ vector< vector<int > > dp ( m+1 , vector<int > ( n+1 , 0 ) );
168+
169+ // 状态转移
170+ // i、j都从1开始遍历 因为下面的操作中都会-1 相当于从0开始
171+ for ( int i=1 ; i<m+1 ; i++ ){
172+ for ( int j=1 ; j<n+1 ; j++ ){
173+ // 如果text1和text2相同
174+ // 就在它们的前一位基础上加一
175+ // 如果不同 只能在之前的两者中去最大
176+ dp[i][j] = (text1[i-1] == text2[j-1]) ? dp[i-1][j-1] + 1 : max( dp[i-1][j] , dp[i][j-1] );
177+ }
178+ }
179+
180+ // 返回最终右下角的值
181+ return dp[m][n];
182+ }
183+ };
184+ ```
185+
152186[ Shawn] ( https://github.com/Shawn-Hx ) 提供 Java 代码:
153187
154188``` java
@@ -173,3 +207,4 @@ public int longestCommonSubsequence(String text1, String text2) {
173207}
174208```
175209
210+
You can’t perform that action at this time.
0 commit comments