// 程序员面试题精选100题(46)-对称子字符串的最大长度.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
int symmetry(string str,int begin,int end)// surppose begin is less than end
{
//int len=0;
while(begin>=0&&end<str.length()&&str[begin]==str[end])
{
//len++;
begin--;
end++;
}
return end-begin-1;//end-1-(begin-1)+1
}
int GetLongestSymmetricalLength_2(char* pString)//other's
{
if(pString == NULL)
return 0;
int symmeticalLength = 1;
char* pChar = pString;
while(*pChar != '\0')
{
// Substrings with odd length
char* pFirst = pChar - 1;
char* pLast = pChar + 1;
while(pFirst >= pString && *pLast != '\0' && *pFirst == *pLast)
{
pFirst--;
pLast++;
}
int newLength = pLast - pFirst - 1;
if(newLength > symmeticalLength)
symmeticalLength = newLength;
// Substrings with even length
pFirst = pChar;
pLast = pChar + 1;
while(pFirst >= pString && *pLast != '\0' && *pFirst == *pLast)
{
pFirst--;
pLast++;
}
newLength = pLast - pFirst - 1;
if(newLength > symmeticalLength)
symmeticalLength = newLength;
pChar++;
}
return symmeticalLength;
}
int _tmain(int argc, _TCHAR* argv[])
{
char* str="google";
int maxlen=0;
for (int i=0;str[i]!='\0';i++)
{
int temp1 = symmetry(str,i,i);
int temp2 = symmetry(str,i,i+1);
//cout<<temp<<" ";
if (max(temp1,temp2)>maxlen)
{
maxlen=max(temp1,temp2);
}
}
cout<<maxlen<<endl;
cout<<GetLongestSymmetricalLength_2(str)<<endl;
system("pause");
return 0;
}
程序员面试题精选100题(46)-对称子字符串的最大长度
最新推荐文章于 2021-02-13 03:47:45 发布