给定一个字符串输出所有长度至少为2的回文子串。回文子串即从左往右输出和从右往左输出结果是一样的字符串比如:abbacccdeedccc都是回文字符串。用C++语言编写上述代码
#include <iostream>
#include <string>
using namespace std;
bool isPalindrome(string s, int start, int end) {
while (start < end) { // 判断是否回文
if (s[start] != s[end]) {
return false;
}
start++;
end--;
}
return true;
}
void findPalindromicSubstring(string s) {
int len = s.size();
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
if (isPalindrome(s, i, j)) { // 判断是否回文
cout << s.substr(i, j - i + 1) << endl; // 输出回文子串
}
}
}
}
int main() {
string s;
cin >> s;
findPalindromicSubstring(s);
return 0;
}
``
原文地址: https://www.cveoy.top/t/topic/hcPH 著作权归作者所有。请勿转载和采集!