Skip to content

Commit 89c5b8f

Browse files
committed
Time: 39 ms (27.60%), Space: 15.4 MB (18.59%) - LeetHub
1 parent c7da196 commit 89c5b8f

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
class Solution {
2+
public:
3+
string shortestCommonSupersequence(string x, string y) {
4+
int n = x.size();
5+
int m = y.size();
6+
vector<int> row(y.size()+1, -1);
7+
vector<vector<int>> dp(x.size()+1,row);
8+
for(int i=0;i<n;i++){
9+
for(int j=0;j<m;j++){
10+
if(i==0 || j==0){
11+
dp[i][j]=0;
12+
}
13+
}
14+
}
15+
for(int i=1;i<=n;i++){
16+
for(int j = 1;j<=m;j++){
17+
if(x[i-1] == y[j - 1]){
18+
dp[i][j] = 1 + dp[i-1][j-1];
19+
}
20+
else {
21+
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
22+
}
23+
}
24+
}
25+
string ans="";
26+
int i = n, j = m;
27+
while(i > 0 and j>0){
28+
if(x[i-1]==y[j-1]){
29+
ans = x[i-1] + ans;
30+
i--;
31+
j--;
32+
} else if(dp[i-1][j] > dp[i][j-1]){
33+
ans = x[i-1] + ans;
34+
i--;
35+
} else {
36+
ans = y[j-1] + ans;
37+
j--;
38+
}
39+
}
40+
while(i>0){
41+
ans = x[i-1] + ans;
42+
i--;
43+
}
44+
while(j>0) {
45+
ans = y[j-1] + ans;
46+
j--;
47+
}
48+
return ans;
49+
}
50+
};

0 commit comments

Comments
 (0)