L2-008. 最长对称子串
2018-03-17 23:42
288 查看
对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定"Is PAT&TAP symmetric?",最长对称子串为"s PAT&TAP s",于是你应该输出11。输入格式:输入在一行中给出长度不超过1000的非空字符串。输出格式:在一行中输出最长对称子串的长度。输入样例:
一切尽在代码中啊,说一下错误的地方吧
1.两种四处边界问题要处理好2.不要忽略只有一个字符的时候
3.分奇偶数做
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main ()
{
char s[1005];
gets(s);
int l=strlen(s);
int a,b,ans,max=1; //注意max=1,当一个字符时,ans=0,但是正确答案是1
for (int i=1;i<l-1;i++) //边界问题,i=0时会出现a[-1],i=l-1时会出现a[l]
{
a=i-1,b=i+1;ans=1; //相当于字符串个数为奇数,加上最中间的那个
while (s[a]==s[b]&&a>=0&&b<l) //还是要注意边界问题
{
a--;b++;ans+=2; //左右各加一个
}
if (ans>max) max=ans;
}
for (int i=0;i<l-1;i++)
{
a=i;b=i+1;ans=0;
while (s[a]==s[b]&&a>=0&&b<l)
{
a--;b++;ans+=2;
}
if (ans>max) max=ans; //此处的max是上面的max(max,ans)
}
cout<<max<<endl;
}
Is PAT&TAP symmetric?输出样例:
11
一切尽在代码中啊,说一下错误的地方吧
1.两种四处边界问题要处理好2.不要忽略只有一个字符的时候
3.分奇偶数做
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main ()
{
char s[1005];
gets(s);
int l=strlen(s);
int a,b,ans,max=1; //注意max=1,当一个字符时,ans=0,但是正确答案是1
for (int i=1;i<l-1;i++) //边界问题,i=0时会出现a[-1],i=l-1时会出现a[l]
{
a=i-1,b=i+1;ans=1; //相当于字符串个数为奇数,加上最中间的那个
while (s[a]==s[b]&&a>=0&&b<l) //还是要注意边界问题
{
a--;b++;ans+=2; //左右各加一个
}
if (ans>max) max=ans;
}
for (int i=0;i<l-1;i++)
{
a=i;b=i+1;ans=0;
while (s[a]==s[b]&&a>=0&&b<l)
{
a--;b++;ans+=2;
}
if (ans>max) max=ans; //此处的max是上面的max(max,ans)
}
cout<<max<<endl;
}
相关文章推荐
- L2-008. 最长对称子串
- L2-008. 最长对称子串
- L2-008. 最长对称子串
- PAT ~ L2-008. 最长对称子串 (Manacher)
- L2-008. 最长对称子串
- L2-008. 最长对称子串-PAT团体程序设计天梯赛GPLT
- L2-008. 最长对称子串 (最长公共子串简单应用)
- PAT L2-008. 最长对称子串(25) (暴力,Manacher算法和DP解决)
- 天梯赛L2-008最长对称子串
- pat L2-008. 最长对称子串
- L2-008. 最长对称子串
- L2-008. 最长对称子串
- L2-008. 最长对称子串
- L2-008. 最长对称子串
- L2-008. 最长对称子串
- L2-008. 最长对称子串
- L2-008. 最长对称子串
- L2-008. 最长对称子串
- L2-008. 最长对称子串
- Java - PAT - L2-008. 最长对称子串 Manacher算法