Skip to content

Commit 312ab11

Browse files
committed
Runtime: 22 ms (Top 70.57%) | Memory: 10.5 MB (Top 99.25%)
1 parent 03d4529 commit 312ab11

File tree

1 file changed

+62
-61
lines changed

1 file changed

+62
-61
lines changed
Lines changed: 62 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -1,70 +1,71 @@
1-
class Solution
1+
// Runtime: 22 ms (Top 70.57%) | Memory: 10.5 MB (Top 99.25%)
2+
class Solution
23
{
3-
string LCS(string str1, string str2, int m, int n)
4-
{
5-
int t[m+1][n+1];
6-
string ans = "";
7-
for(int i = 0;i < m+1; ++i)
8-
{
9-
for(int j = 0; j< n+1; ++j)
10-
{
11-
if(i == 0 || j == 0)
12-
t[i][j] = 0;
13-
}
14-
}
4+
string LCS(string str1, string str2, int m, int n)
5+
{
6+
int t[m+1][n+1];
7+
string ans = "";
8+
for(int i = 0;i < m+1; ++i)
9+
{
10+
for(int j = 0; j< n+1; ++j)
11+
{
12+
if(i == 0 || j == 0)
13+
t[i][j] = 0;
14+
}
15+
}
1516

16-
for(int i = 1; i < m+1; ++i)
17-
{
18-
for(int j = 1; j < n+1; ++j)
19-
{
20-
if(str1[i-1] == str2[j-1])
21-
t[i][j] = 1 + t[i-1][j-1];
22-
else
23-
t[i][j] = max(t[i-1][j], t[i][j-1]);
24-
}
25-
}
26-
int i = m, j = n;
27-
while(i > 0 && j > 0)
28-
{
29-
if(str1[i-1] == str2[j-1])
30-
{
31-
ans.push_back(str1[i-1]);
32-
--i;
33-
--j;
34-
}
17+
for(int i = 1; i < m+1; ++i)
18+
{
19+
for(int j = 1; j < n+1; ++j)
20+
{
21+
if(str1[i-1] == str2[j-1])
22+
t[i][j] = 1 + t[i-1][j-1];
23+
else
24+
t[i][j] = max(t[i-1][j], t[i][j-1]);
25+
}
26+
}
27+
int i = m, j = n;
28+
while(i > 0 && j > 0)
29+
{
30+
if(str1[i-1] == str2[j-1])
31+
{
32+
ans.push_back(str1[i-1]);
33+
--i;
34+
--j;
35+
}
3536

36-
else if(t[i][j-1] > t[i-1][j])
37-
{
38-
ans.push_back(str2[j-1]);
39-
--j;
40-
}
37+
else if(t[i][j-1] > t[i-1][j])
38+
{
39+
ans.push_back(str2[j-1]);
40+
--j;
41+
}
4142

42-
else
43-
{
44-
ans.push_back(str1[i-1]);
45-
--i;
46-
}
47-
}
48-
while( i > 0)
49-
{
50-
ans.push_back(str1[i-1]);
51-
--i;
52-
}
53-
while( j > 0)
54-
{
55-
ans.push_back(str2[j-1]);
56-
--j;
57-
}
58-
reverse(ans.begin(),ans.end());
59-
return ans;
60-
}
43+
else
44+
{
45+
ans.push_back(str1[i-1]);
46+
--i;
47+
}
48+
}
49+
while( i > 0)
50+
{
51+
ans.push_back(str1[i-1]);
52+
--i;
53+
}
54+
while( j > 0)
55+
{
56+
ans.push_back(str2[j-1]);
57+
--j;
58+
}
59+
reverse(ans.begin(),ans.end());
60+
return ans;
61+
}
6162

6263
public:
63-
string shortestCommonSupersequence(string str1, string str2) {
64+
string shortestCommonSupersequence(string str1, string str2) {
6465

65-
int m = str1.length();
66-
int n = str2.length();
66+
int m = str1.length();
67+
int n = str2.length();
6768

68-
return LCS(str1, str2, m ,n);
69-
}
69+
return LCS(str1, str2, m ,n);
70+
}
7071
};

0 commit comments

Comments
 (0)