-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode-LongestPalindromicSubstring.cpp
More file actions
60 lines (43 loc) · 1.45 KB
/
LeetCode-LongestPalindromicSubstring.cpp
File metadata and controls
60 lines (43 loc) · 1.45 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Solution {
public:
string longestPalindrome(const string& s) {
if (s.empty()) return "";
int n = s.size();
//number of palindromic substrings of odd length with center at i.
vector<int> odd(n);
//number of palindromic substrings of even length with center at i.
vector<int> even(n-1);
for (int i = 0; i < n; ++i) {
int x = 0;
while (i - x >= 0 && i + x < n && s[i-x] == s[i+x]) {
odd[i]++;
++x;
}
if (i == n - 1) continue;
if (s[i] != s[i+1]) continue;
even[i] = 1;
x = 1;
while (i - x >= 0 && i + x + 1 < n && s[i-x] == s[i+x+1]) {
even[i]++;
++x;
}
}
int len = 0;
int l = 0;
for (int i = 0;i < odd.size(); ++i) {
int length = 2 * odd[i] - 1;
if (length > len) {
len = length;
l = i - len / 2;
}
}
for (int i = 0; i < even.size(); ++i) {
int length = 2 * even[i];
if (length > len) {
len = length;
l = i - ((len / 2) - 1);
}
}
return s.substr(l, len);
}
};