/
longest-palindromic-substring.cpp
68 lines (56 loc) · 1.42 KB
/
longest-palindromic-substring.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <string>
#include <vector>
#include <iostream>
using namespace std;
class Solution
{
public:
string longestPalindrome(string s)
{
if (s.size() == 0) {
return 0;
}
int n = s.size();
vector<int> f(n);
int len = 1;
int start = 0;
for (int i = n - 1; i >= 0; --i) {
f[i] = 1;
for (int j = n - 1; j > i; --j) {
if (i == j - 1) {
if (s[i] == s[j]) {
f[j] = 2;
if (len < f[j]) {
len = f[j];
start = i;
}
} else {
f[j] = 0;
}
continue;
}
if (f[j - 1] > 0) {
if (s[i] == s[j]) {
f[j] = f[j - 1] + 2;
if (len < f[j]) {
len = f[j];
start = i;
}
} else {
f[j] = 0;
}
} else {
f[j] = 0;
}
}
}
return s.substr(start, len);
}
};
int main(int argc, char *argv[])
{
Solution solver;
string s("ccc");
cout << solver.longestPalindrome(s) << endl;
return 0;
}