现在的位置: 首页 > 综合 > 正文

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

2013年12月02日 ⁄ 综合 ⁄ 共 1302字 ⁄ 字号 评论关闭
/*

给定只包含括号字符'('和 ')''的字符串,请找出最长的有效括号内子括号的长度。 
举几个例子如下: 例如对于"( ()",最长的有效的括号中的子字符串是"()" ,有效双括号数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;
} 

抱歉!评论已关闭.