-
Notifications
You must be signed in to change notification settings - Fork 481
/
0005.cpp
38 lines (37 loc) · 1.01 KB
/
0005.cpp
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
#include <string>
#include <iostream>
using namespace std;
static int x = []() {std::ios::sync_with_stdio(false); cin.tie(0); return 0; }();
class Solution
{
public:
string longestPalindrome(string s)
{
if (s.empty()) return "";
if (s.size() == 1) return s;
int len = s.size(), start = 0, maxLength = 1, left, right;
for (unsigned int i = 0; i < len && len - i > maxLength / 2;)
{
left = right = i;
while (right < len - 1 && s[right + 1] == s[right]) ++right;
i = right + 1;
while (right < len - 1 && left > 0 && s[right + 1] == s[left - 1])
{
++right;
--left;
}
if (maxLength < right - left + 1)
{
start = left;
maxLength = right - left + 1;
}
}
return s.substr(start, maxLength);
}
};
int main()
{
string s = "babad";
cout << Solution().longestPalindrome(s) << endl;
return 0;
}