最长回文子串 C++
时间: 2023-11-14 15:07:49 浏览: 104
最长回文子串是指一个字符串中最长的回文子串,即正着读和倒着读都一样的子串。下面是 C++ 的实现代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
string longestPalindrome(string s) {
int n = s.size();
if (n < 2) return s;
int start = 0, maxLen = 1;
for (int i = 0; i < n; ) {
if (n - i <= maxLen / 2) break;
int j = i, k = i;
while (k < n - 1 && s[k + 1] == s[k]) ++k;
i = k + 1;
while (k < n - 1 && j > 0 && s[k + 1] == s[j - 1]) {
++k;
--j;
}
int newLen = k - j + 1;
if (newLen > maxLen) {
start = j;
maxLen = newLen;
}
}
return s.substr(start, maxLen);
}
int main() {
string s = "babad";
cout << longestPalindrome(s) << endl; // "bab" or "aba"
return 0;
}
```
阅读全文