-
Notifications
You must be signed in to change notification settings - Fork 0
/
1092. Shortest Common Supersequence.txt
39 lines (36 loc) · 1.18 KB
/
1092. Shortest Common Supersequence.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
https://leetcode.com/problems/shortest-common-supersequence/
class Solution {
private:
string subs(string str1,string str2){
string dp[str1.size() + 1][str2.size() + 1];
for(int i = 0 ; i < str1.size(); i++){
for(int j = 0; j < str2.size(); j++){
if(str1[i] == str2[j]){
dp[i+1][j+1] = dp[i][j] + str1[i];
}
else{
dp[i+1][j+1] = dp[i][j+1].size() > dp[i+1][j].size() ? dp[i][j+1] : dp[i+1][j];
}
}
}
return dp[str1.size()][str2.size()];
}
public:
string shortestCommonSupersequence(string str1, string str2) {
if(str1.size() == 0)
return "";
int i = 0;
int j = 0;
string res = "";
for(char c : subs(str1,str2)){
while(str1[i] != c)
res+= str1[i++];
while(str2[j] != c)
res+=str2[j++];
res+=c;
i++;
j++;
}
return res + str1.substr(i,str1.size()) + str2.substr(j,str2.size());
}
};