求一个字符串中包含的对称子字符串的最大长度(两种方案,一个时间复杂度n2,一个时间复杂度n3)

来源:互联网 发布:linux home代表什么 编辑:程序博客网 时间:2024/05/21 21:31
//求一个字符串中包含的对称子字符串的最大长度
//author:ZR
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;




string returnString(string str,int i,int j){
string returnStr="";
if(i>j)
return returnStr;
else{
for(int k=i;k!=j+1;k++)
returnStr+=str[k];
}
return returnStr;
}
//弱一点的判断字符串对称的函数
//这个一看就是web开发写多了。。。注意代码质量啊
bool symmetryOrNot(string str){
int length=str.size();
for(int i=0;i!=length/2;i++){
if(str[i]!=str[length-i-1])
return false;
}
return true;
}
//牛一点的判断字符串对称的函数
//调用方式:isSymmetrical(&str[0],&str[str.size()-1])
bool isSymmetrical(char* pBegin,char* pEnd){
if(pBegin==NULL || pEnd==NULL || pBegin>pEnd)
return false;
while(pBegin<pEnd){
if(*pBegin!=*pEnd)
return false;
pBegin++;
pEnd--;
}
return true;
}








//以下函数所属解决方案的时间复杂度为n的三次方
void n3Time(){
cout<<"请输入一个字符串,将输出该字符串最长对称子串及其长度:";
string str;
string ziStr="";
cin>>str;
int max=1;//记录最长的对称字串的长度
for(int i=0;i!=str.size();i++)
for(int j=i+1;j!=str.size();j++){
if(symmetryOrNot(returnString(str,i,j))&&(returnString(str,i,j).size()>max)){
max=returnString(str,i,j).size();
ziStr=returnString(str,i,j);
}
}
cout<<endl<<"最大长度为:"<<max<<endl;
cout<<"对应字串为:"<<ziStr;
}
//以下函数所属解决方案的时间复杂度为n的2次方
void n2Time(){
cout<<"请输入一个字符串,将输出该字符串最长对称子串及其长度:";
string str;
cin>>str;
int length=str.size();
int symmetricalLength=1;
int max=1;
int start;
int end;
for(int i=1;i<length;i++){
start=i-1;
end=i+1;
while(start>=0&&end<length&&str[start]==str[end]){
start--;
end++;
}
symmetricalLength=end-start-1;
if(symmetricalLength>max)
max=symmetricalLength;
}
for(int i=0;i<length-1;i++){
start=i;
end=i+1;
while(start>=0&&end<length&&str[start]==str[end]){
start--;
end++;
}
symmetricalLength=end-start-1;
if(symmetricalLength>max)
max=symmetricalLength;
}
cout<<endl<<max;
}


int main(){
n2Time();
return 0;
}

原创粉丝点击