栈
一种先进后出的数据结构。
复杂度单次通常为 O ( 1 ) O(1) O(1)
用途:括号匹配,倒序问题等
例子:
序列A:{1,2,3,4,5}依次入栈再同一出栈,顺序为A’:{5,4,3,2,1}
代码:
插入:
void insert(int x){st[++top]=x;
}
删除:
void erase(int x){--top;
}
查找栈首:
int Top(){return st[top];
}
括号匹配。
每次如果搜到)
判断栈头是否为 (
即可。例子
(((())))
步骤:
- 搜到
(
入栈 - 搜到
(
入栈 - 搜到
(
入栈 - 搜到
(
入栈 - 搜到
)
判断栈首为)
弹出栈首 - 搜到
)
判断栈首为)
弹出栈首 - 搜到
)
判断栈首为)
弹出栈首 - 搜到
)
判断栈首为)
弹出栈首 - 最后栈空说明是一个匹配的括号序列
代码:
#include<iostream>using namespace std;
const int N=1e5+5;
char st[N];
int top=0;
int main(){string s;cin>>s;for(auto c:s){if(c=='('){st[++top]=c;}else{if(st[top]=='('){--top;}else{cout<<"No";return 0;}}}if(top==0){cout<<"Yes";}else{cout<<"No";}return 0;
}