对称子字符串的最大长度
输入一个字符串,输出该字符串中对称的子字符串的最大长度。比如输入字符串“google”,由于该字符串里最长的对称子字符串是“goog”,因此输出4。
#include<stdio.h>
#include<string>
#include<iostream>
using namespace std;
//char s[] = "google";
//判断一个字符串是否是对称的
bool IsSymmetricalString(char* pstart ,char* pend)
{
//两个指针不能为空
//头指针不能大于尾指针
if (pstart == NULL || pend == NULL || pstart > pend)
return false;
//头指针小于尾指针时判断两位指针的值是否相等
while (pstart < pend)
{
if (*pstart != *pend)
return false;
else
{
//头指针指向下一个,类似于s[0++]
pstart++;
//尾指针指向上一个,类似于s[len--]
pend--;
}
}
return true;
}
//求最大对称子串的长度
//从内向外比较
//时间复杂度O(n²)
int MaxStrIntoOut(char* pstring)
{
int maxlength = 1;
char* pchar = pstring + 1;//pchar=pstring地址-1的位置
while (*pchar != '\0')
{
char* pfirst = pchar - 1;//pchar地址-1的位置
char* psecond = pchar + 1;//pchar地址+1的位置
//
while (pfirst > pstring && psecond < &pstring[strlen(pstring) - 1] && *pfirst == *psecond)
{
pfirst--;
psecond++;
}
int templen = psecond - pfirst + 1;
if (templen > maxlength)
maxlength = templen;
pfirst = pchar - 1;
psecond = pchar;
while (pfirst > pstring && psecond < &pstring[strlen(pstring) - 1] && *pfirst == *psecond)
{
pfirst--;
psecond++;
}
templen = psecond - pfirst + 1;
if (templen > maxlength)
{
maxlength = templen;
}
pchar++;
}
return maxlength;
}
//从头遍历字符串
//时间复杂度O(n³)
int MaxStrOnetoEnd(char* pstring)
{
if (pstring == NULL)
return 0;
int maxlen = 1;
int len = strlen(pstring);
char* pfirst = pstring;
while (pfirst < &pstring[len - 1])
{
char* psecond = pfirst + 1;
while (psecond <= &pstring[len - 1])
{
if (IsSymmetricalString(pfirst, psecond))
{
int templen = psecond - pfirst + 1;
if (templen > maxlen)
{
maxlen = templen;
}
}
psecond++;
}
pfirst++;
}
return maxlen;
}
void main()
{
cout << "请输入字符串!" << endl;
char* s = new char[1000];
cin >> s;
cout << "对称字符串的最大长度是:" << endl;
cout << MaxStrOnetoEnd(s) << endl;
delete[] s;
}