File tree 1 file changed +7
-6
lines changed
scripts/algorithms/L/Longest Palindromic Substring
1 file changed +7
-6
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 168 ms (Top 52.00%) | Memory: 173.7 MB (Top 19.81%)
1
2
class Solution {
2
3
public:
3
4
string longestPalindrome (string s) {
4
5
if (s.size () <= 1 ) return s;
5
-
6
+
6
7
string longest = " " ;
7
-
8
+
8
9
for (int i = 0 ; i < s.size (); i++) {
9
10
string sub1 = expand (s, i, i+1 );
10
11
string sub2 = expand (s, i, i);
11
-
12
+
12
13
string sub3 = sub1.size () > sub2.size () ? sub1 : sub2;
13
-
14
+
14
15
if (sub3.size () > longest.size ()) {
15
16
longest = sub3;
16
17
}
17
18
}
18
19
return longest;
19
20
}
20
-
21
+
21
22
string expand (string s, int i, int j) {
22
23
while (j < s.size () && i >= 0 && s[i] == s[j]) {
23
24
i--;
@@ -26,4 +27,4 @@ class Solution {
26
27
// Add 1 to i and subtract 1 from j because the range is expanded by 1 on each side before it ends
27
28
return s.substr (i+1 , j-i-1 );
28
29
}
29
- };
30
+ };
You can’t perform that action at this time.
0 commit comments