-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode_5.cpp
More file actions
34 lines (32 loc) · 957 Bytes
/
Copy pathleetcode_5.cpp
File metadata and controls
34 lines (32 loc) · 957 Bytes
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
class Solution {
public:
string longestPalindrome(string s) {
int l, r;
int maxLen = 0;
string res;
for (int i = 0; i < s.length(); i++) {
l = i;
r = i;
while (l >= 0 && r < s.length() && s[l] == s[r]) {
if ((r - l + 1) > maxLen) {
res = s.substr(l, r - l + 1); // Use substr
maxLen = r - l + 1;
}
l--;
r++;
}
// Case 2: Even length palindrome
l = i;
r = i + 1;
while (l >= 0 && r < s.length() && s[l] == s[r]) {
if ((r - l + 1) > maxLen) {
res = s.substr(l, r - l + 1); // Use substr
maxLen = r - l + 1;
}
l--;
r++;
}
}
return res; // Ensure this is at the end of the function
}
};