挑战编程: 最长有效括号的长度

/*

给定只包含括号字符'('和 ')''的字符串,请找出最长的有效括号内子括号的长度。 
举几个例子如下: 例如对于"( ()",最长的有效的括号中的子字符串是"()" ,有效双括号数1个,故它的长度为 2。  
再比如对于字符串") () () )",其中最长的有效的括号中的子字符串是"() ()",有效双括号数2个,故它的长度为4。  
再比如对于"( () () )",它的长度为6。          
换言之,便是有效双括号"()"数的两倍。 
给定函数原型int longestValidParentheses(string s),请完成此函数,实现上述功能。 
*/

#include <iostream>
#include <string>

using namespace std;

int longestValidParentheses(string s);

int main()
{
	
	while (1)
	{
		string str;
		cin >> str;
		int result = longestValidParentheses(str); 
		cout << result;
	}
	
	getchar();
	return 0;
}

int longestValidParentheses(string s)
{	
	int result = 0;
	int lenIndex = s.size();
	int indexResult[1024] = {0};
	
	for (int i = 0; i < lenIndex; i ++)
	{
		indexResult[i] = i;
	}
	
	int index = 0;
	string content = s;

	for (int i = 0; i < lenIndex - 1;)
	{
		char str[2];
		str[0] = content[indexResult[i]];
		str[1] = content[indexResult[i+1]];

		if (content[indexResult[i]] == '(' && content[indexResult[i+1]] == ')')
		{
			//result = indexResult[i+1] - indexResult[i] + 1;
			for (int j = i; j < lenIndex; j++)
			{
				indexResult[j] = indexResult[j+2];
			}

			lenIndex = lenIndex - 2;
			i = 0;
		}
		else i ++;
	}
	if (lenIndex == 0)
	{
		result = s.size();
	}
	else if (lenIndex == s.size())
	{
		result = 0;
	}
	else
	{
		if(indexResult[0] != 0)
		{
			for (int i = lenIndex; i > 0; i--)
			{
				indexResult[i] = indexResult[i - 1];
			}
			indexResult[0] = -1;
			lenIndex ++;
		}

		if (indexResult[lenIndex - 1] != s.size() - 1)
		{
			indexResult[lenIndex] = s.size();
			lenIndex ++;
		}
		
		for(int i = 0; i < lenIndex - 1; i ++)
		{
			int max = indexResult[i+1] - indexResult[i] - 1;
			if (max > result)
				 result = max ;
		}
	}
	
	return result;
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不会唱歌的老樊

老少爷们,来个赏!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值