-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprob5.cpp
More file actions
40 lines (36 loc) · 847 Bytes
/
prob5.cpp
File metadata and controls
40 lines (36 loc) · 847 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
35
36
37
38
39
40
/*
Medium - Longest Palindromic Substring
https://leetcode.com/problems/longest-palindromic-substring/description
*/
#include <string>
using namespace std;
class Solution
{
public:
string expandAroundCenter(const string &s, int left, int right)
{
while (left >= 0 && right < s.length() && s[left] == s[right])
{
left--;
right++;
}
// Substring from left+1 to right-1 (length = right - left - 1)
return s.substr(left + 1, right - left - 1);
}
string longestPalindrome(string s)
{
string res = "";
for (int i = 0; i < s.length(); ++i)
{
// Odd-length palindrome
string odd = expandAroundCenter(s, i, i);
if (odd.length() > res.length())
res = odd;
// Even-length palindrome
string even = expandAroundCenter(s, i, i + 1);
if (even.length() > res.length())
res = even;
}
return res;
}
};