题目的大概描述是这样的:
有一段字符串设置为密码,要求输入的字符串最长的对称的字符串 为 有效密码。
比如 输入 aba, aa, abba, w2gtttg1, abaaab 等,其有效密码分别为:aba, aa, abba, gtttg, baaab.
下面是我写的实现代码,工作环境是VC6.0. (希望高手多多指教~)
// test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
void getValidString(const std::string inputStr, std::string& outputStr, int& length);
int main(int argc, char* argv[])
{
//printf("Hello World!\n");
std::string inputStr;
cin >> inputStr;
std::string outputStr;
int length = 0;
getValidString(inputStr, outputStr, length);
cout << outputStr << " - " << length << endl;
return 0;
}
void getValidString(const std::string inputStr, std::string& outputStr, int& length)
{
int inLen = inputStr.length();
length = 0;
if (inLen <= 0)
{
return;
}
for (int i=0; i<inLen; ++i)
{
for (int j=0; j<(inLen-i)/2; ++j)
{
bool isCode1 = false;
bool isCode2 = false;
// check if the current check subString is the valid code string
for (int k=0; k<=j; k++)
{
// check second mode: ababa
if (i+j+k+2 >= inLen)
{
isCode2 = false;
break;
}
if(inputStr[i+j-k] == inputStr[i+j+k+2])
{
isCode2 = true;
}
else
{
isCode2 = false;
break;
}
}
// get the valid string and length
if (isCode2 && 2*(j+1) + 1 > length)
{
length = 2*(j+1) + 1;
outputStr = inputStr.substr(i, length);
}
else
{
for (int k=0; k<=j; k++)
{
// check first mode:abba
if(inputStr[i+j-k] == inputStr[i+j+k+1])
{
isCode1 = true;
}
else
{
isCode1 = false;
break;
}
}
if(isCode1 && 2*(j+1) > length)
{
length = 2*(j+1);
outputStr = inputStr.substr(i, length);
}
} //end of esle
}//end of for j
}//end of for i
}