括号模拟
括号画家
https://ac.nowcoder.com/acm/contest/1012/A
首先在这里检讨下自己,今天实在是好堕落啊@……%……&~
判断括号是否匹配成功,肯定要用到栈这个数据结构,当我们匹配到 c 字符时,我们判断和栈顶元素是否匹配,如果匹配的话,我们就把这个栈顶元素删掉,当栈顶元素不匹配时我们让 c 字符进栈。
if(stk.size())res = max(res,i - stk.top()); // else res = max(res , i + 1);
如果栈不为空,那么我们看这个字符到栈顶元素的距离 ,为什么不加 + 1 呢? 是因为我们在运算之前就已经删掉了栈顶元素 比如 4 5 是匹配的 ,删掉栈顶元素4 会变为2 , 5 - 3 = 2 ,为当时的答案。
在栈和队列的操作中一定要注意栈或者队列是否为空
在栈和队列的操作中一定要注意栈或者队列是否为空
在栈和队列的操作中一定要注意栈或者队列是否为空
真的好菜啊&()*……#&%!#*&
#include<bits/stdc++.h> #define pr printf #define sc scanf #define fur(i,a,b) for(int i = a; i<= b ;i++) #define fdr(i,a,b) for(int i = a; i>= b ;i--) using namespace std; typedef long long ll; const int N = 100000 + 5 ; char str[N]; int main() { freopen("in.txt","r",stdin); scanf("%s",str); int n = strlen(str); int res = 0 ; stack <int> stk; for(int i = 0 ;i < n ; i ++) { char c = str[i] ; if(stk.size() && c == ']' && str[stk.top()]=='[')stk.pop(); else if(stk.size() && c == '}' && str[stk.top()]=='{')stk.pop(); else if(stk.size() && c == ')' && str[stk.top()]=='(')stk.pop(); else stk.push(i); if(stk.size())res = max(res,i - stk.top()); // else res = max(res , i + 1); } printf("%d",res); return 0; }