根据输入的字符串,判断并输出有效的字符串的长度,和该字符串。vc++

题目的大概描述是这样的:

有一段字符串设置为密码,要求输入的字符串最长的对称的字符串 为 有效密码。

比如 输入 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

}















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值