-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy path5.longest-palindromic-substring.cpp
More file actions
146 lines (129 loc) · 3.21 KB
/
5.longest-palindromic-substring.cpp
File metadata and controls
146 lines (129 loc) · 3.21 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
// Tag: Two Pointers, String, Dynamic Programming
// Time: O(N)
// Space: O(N)
// Ref: -
// Note: -
// Given a string s, return the longest palindromic substring in s.
//
// Example 1:
//
// Input: s = "babad"
// Output: "bab"
// Explanation: "aba" is also a valid answer.
//
// Example 2:
//
// Input: s = "cbbd"
// Output: "bb"
//
//
// Constraints:
//
// 1 <= s.length <= 1000
// s consist of only digits and English letters.
//
//
class Solution {
public:
string longestPalindrome(string s) {
int n = s.size();
vector<vector<bool>> dp(n, vector<bool>(n, false));
int start = 0;
int length = 1;
for (int i = 0; i < n; i++) {
dp[i][i] = true;
}
for (int i = 1; i < n; i++) {
if (s[i - 1] == s[i]) {
dp[i - 1][i] = true;
start = i - 1;
length = 2;
}
}
for (int l = 3; l <= n; l++) {
for (int i = 0; i <= n - l; i++) {
int j = l + i - 1;
if (s[i] == s[j] && dp[i + 1][j - 1]) {
dp[i][j] = true;
if (length < j - i + 1) {
length = j - i + 1;
start = i;
}
}
}
}
return s.substr(start, length);
}
};
class Solution {
public:
string longestPalindrome(string s) {
int n = s.size();
string res;
for (int i = 0; i < n; i++) {
string tmp = expand(s, i, i);
if (tmp.size() > res.size()) {
res = tmp;
}
tmp = expand(s, i, i + 1);
if (tmp.size() > res.size()) {
res = tmp;
}
}
return res;
}
string expand(string &s, int l, int r) {
while (l >=0 && r < s.size()) {
if (s[l] == s[r]) {
l --;
r ++;
} else {
break;
}
}
int start = l + 1;
int length = r - start;
return s.substr(start, length);
}
};
class Solution {
public:
string longestPalindrome(string s) {
string t = buildString(s);
int n = t.size();
vector<int> p(n, 0);
int center = 0;
int right_x = 0;
for (int i = 0; i < n; i++) {
int mirror_j = 2 * center - i;
if (i < right_x) {
p[i] = min(right_x - i, p[mirror_j]);
}
while (i + p[i] + 1 < n && i - p[i] - 1 >= 0 && t[i + p[i] + 1] == t[i - p[i] - 1]) {
p[i]++;
}
if (right_x < i + p[i]) {
center = i;
right_x = i + p[i];
}
}
int max_center = 0;
int max_r = 0;
for (int i = 0; i < n; i++) {
if (max_r < p[i]) {
max_r = p[i];
max_center = i;
}
}
int start = (max_center - max_r) / 2;
return s.substr(start, max_r);
}
string buildString(string s) {
string t = "#";
for (auto x: s) {
t += x;
t += '#';
}
return t;
}
};