总时间限制:
-
描述
-
给定一个字符串,输出所有长度至少为2的回文子串。
回文子串即从左往右输出和从右往左输出结果是一样的字符串,比如:abba,cccdeedccc都是回文字符串。
输入
- 一个字符串,由字母或数字组成。长度500以内。 输出
-
输出所有的回文子串,每个子串一行。
子串长度小的优先输出,若长度相等,则出现位置靠左的优先输出。
样例输入
-
123321125775165561
样例输出
-
33 11 77 55 2332 2112 5775 6556 123321 165561
-
思路:从第一个字符开始比较,先从两个开始,比如12321 先看12 23 32 21 没有就找123 232 321 然后 1232 2321 我用k控制我找的字符数,i控制字符串的循环,然后写一个函数判断是否为回文数,以上分析可知,当跨过k个字符时,i只需比较到len-k。代码如下
-
#include<iostream> #include<cstdlib> #include<algorithm> #include<iomanip> #include<string.h> #include<cstdio> using namespace std; string str; int len; int check(int x,int y)//检查从x到y是不是回文字符串 { int s=x,t=y; while(s<=t) { if(str[s]!=str[t])return 0;//如果不相等直接返回 s++,t--;//继续比较 } for(int i=x;i<=y;i++)//输出这几个字符 cout<<str[i]; cout<<"\n"; return 0; } int main() { getline(cin,str);//接收字符串 len =str.size(); for(int k=1;k<len;k++)//控制比较的字符数目,从两个开始比较 for(int i=0;i<=len-k;i++)//从第一个字符开始 跨过k个字符数 check(i,i+k); }
-