帮我用cpp写一段实现寻找最长回文子串的代码
时间: 2023-04-07 11:03:18 浏览: 92
commonsubstring.rar_数值算法/人工智能_Visual_C++_
好的,以下是用 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" 或 "aba"
return 0;
}
```
希望能够帮到你!
阅读全文