題目的大概描述是這樣的:
有一段字符串設置爲密碼,要求輸入的字符串最長的對稱的字符串 爲 有效密碼。
比如 輸入 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
}