Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit887c77f

Browse files
Add C++ implemention
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parentda4cae3 commit887c77f

File tree

3 files changed

+74
-0
lines changed

3 files changed

+74
-0
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
all:
2+
gcc -O1 -otest lcs.c
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
#include<stdio.h>
2+
#include<stdlib.h>
3+
#include<string.h>
4+
5+
6+
staticintmax(inta,intb)
7+
{
8+
returna>b ?a :b;
9+
}
10+
11+
intlongestCommonSubsequence(char*text1,char*text2)
12+
{
13+
inti,j;
14+
intl1=strlen(text1);
15+
intl2=strlen(text2);
16+
int**dp=malloc((l1+1)*sizeof(int*));
17+
for (i=0;i<l1+1;i++) {
18+
dp[i]=malloc((l2+1)*sizeof(int));
19+
}
20+
memset(dp[0],0, (l2+1)*sizeof(int));
21+
for (i=1;i <=l1;i++) {
22+
dp[i][0]=0;
23+
}
24+
25+
for (i=1;i <=l1;i++) {
26+
for (j=1;j <=l2;j++) {
27+
if (text1[i-1]==text2[j-1]) {
28+
dp[i][j]=dp[i-1][j-1]+1;
29+
}else {
30+
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
31+
}
32+
}
33+
}
34+
returndp[l1][l2];
35+
}
36+
37+
intmain(intargc,char**argv)
38+
{
39+
if (argc!=3) {
40+
fprintf(stderr,"Usage: ./test s1 s2\n");
41+
exit(-1);
42+
}
43+
44+
printf("%d\n",longestCommonSubsequence(argv[1],argv[2]));
45+
return0;
46+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#include<bits/stdc++.h>
2+
3+
usingnamespacestd;
4+
5+
classSolution {
6+
public:
7+
intlongestCommonSubsequence(string text1, string text2) {
8+
int l1 = text1.length();
9+
int l2 = text2.length();
10+
vector<int>dp(l2 +1);
11+
int up =0;
12+
for (int i =1; i <= l1; i++) {
13+
int left_up =0;
14+
for (int j =1; j <= l2; j++) {
15+
up = dp[j];
16+
if (text1[i -1] == text2[j -1]) {
17+
dp[j] = left_up +1;
18+
}else {
19+
dp[j] =max(up, dp[j -1]);
20+
}
21+
left_up = up;
22+
}
23+
}
24+
return dp[l2];
25+
}
26+
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp