-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path最长回文子串
49 lines (46 loc) · 1.31 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
class Solution {
public:
string longestPalindrome(string s) {
vector<vector<bool>> dp(s.size(), vector<bool>(s.size(), false));
for(int i=0;i<s.size();i++){
dp[i][i]=true;
if(i>0) dp[i][i-1]=true;
}
vector<int> result(2, 0);
for(int j=1;j<s.size();j++){
for(int i=j-1;i>=0;i--){
if(s[j]==s[i]&&dp[i+1][j-1]==true){
dp[i][j]=true;
if(j-i>=result[1]-result[0]){
result[1]=j;
result[0]=i;
}
}
}
}
return s.substr(result[0], result[1]-result[0]+1);
}
};
class Solution {
public:
int left = 0;
int maxLength = 0;
string longestPalindrome(string s) {
int result = 0;
for (int i = 0; i < s.size(); i++) {
extend(s, i, i, s.size()); // 以i为中心
extend(s, i, i + 1, s.size()); // 以i和i+1为中心
}
return s.substr(left, maxLength);
}
void extend(const string& s, int i, int j, int n) {
while (i >= 0 && j < n && s[i] == s[j]) {
if (j - i + 1 > maxLength) {
left = i;
maxLength = j - i + 1;
}
i--;
j++;
}
}
};