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;
}