1
- class Solution
1
+ // Runtime: 22 ms (Top 70.57%) | Memory: 10.5 MB (Top 99.25%)
2
+ class Solution
2
3
{
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
+ }
15
16
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
+ }
35
36
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
+ }
41
42
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
+ }
61
62
62
63
public:
63
- string shortestCommonSupersequence (string str1, string str2) {
64
+ string shortestCommonSupersequence (string str1, string str2) {
64
65
65
- int m = str1.length ();
66
- int n = str2.length ();
66
+ int m = str1.length ();
67
+ int n = str2.length ();
67
68
68
- return LCS (str1, str2, m ,n);
69
- }
69
+ return LCS (str1, str2, m ,n);
70
+ }
70
71
};
0 commit comments