LeetCode  32 最长有效括号

LeetCode  32 最长有效括号


使用栈来做这题:

          使用结构体来储存括号和对应的下标。

          通过栈来实现括号的匹配,匹配的弹出或者不入栈。

          用剩下的括号来判断最长的有效括号。

#include <iostream>
#include <map>
#include <queue>
#include <climits>
#include <vector>
#include <stack>
using namespace std;
struct node{
	int ind;
	char c;
};
stack<node> sta;
string input1;
int fff(string s)
{
	for(int a=0;a<s.length();a++)
	{
		if( (!sta.empty()) && sta.top().c == '(' && s[a] == ')') //如果栈中有东西,并且栈顶为( 当前的字符是 ) 就可以把这两个读好配对,弹出栈中的,字符串中的不入栈 
		{
			sta.pop();
		}else //否则就是不满足匹配条件就直接压入栈中 
		{
			node nodetemp ;
			nodetemp.c=s[a];
			nodetemp.ind=a;
			sta.push(nodetemp);
		}
	} 
	
	
	if(sta.size() == 0) //如果全部匹配完了就直接输出字符串长度 
		return s.length();
	else if(sta.size() == s.length())//如果全都没有匹配就是没有可匹配的,输出0 
		return 0;
	else {
		int last = s.length(); //遍历剩下的括号的 字符串下标 ,last表示前一个的下标从字符串长度开始否则会漏掉最后的一个 
		int maxx = 0;   //用来储存长度 
		node qq ;
		while(!sta.empty())
		{
			qq = sta.top();
			sta.pop();
			maxx = last-qq.ind>maxx?last-qq.ind:maxx;  //计算差值 
			last = qq.ind;
		}
		cout<<maxx<<endl;
		maxx = last+1>maxx?last+1:maxx;  //计算最后的差值 
		return maxx-1;
	}
		
}
int main ()
{
	cin>>input1;
	cout<<fff(input1)<<endl;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值