括号匹配---栈的运用

今天数据结构讲了栈
然后找了道水题来试一试

括号匹配1

给出一个括号字符串,然后输出匹配情况
需要对其进行操作使得最后能够匹配成功,求最小的操作次数(可进行的操作有左右括号互换)
传送门
这题和cf一题很像

我先获取字符串,然后遍历字符串
如果是左括号就入栈,如果是右括号,那么看栈里是否为空,栈为空的话,就操作为左括号,如果不为空,就和栈里的左括号进行匹配

#include 
#include 
#include 
#include 
using namespace std;
const int maxn=2e3+5;
int main(){
    char s[maxn];
    int num=1;
    while(~scanf("%s",s)){
        if(s[0]=='-')break;
        int len=strlen(s);
        stack st;
        int cnt=0;
        for(int i=0;i

括号匹配2

传送门
可以的操作是该边一个括号的位置
如果匹配完后栈的大小为2或者为0,而且为2的时候还不能相同,就可以满足条件了

栈操作

#include 
#include 
#include 
#include 
using namespace std;
const int maxn=2e5+5;
int main(){
    char s[maxn];
    int n;
    while(~scanf("%d",&n)){
        scanf("%s",s);
        stack st;
        int cnt=0;
        for(int i=0;i

优化1

栈模拟1+函数的调用

#include 
using namespace std;
typedef long long ll;
string str;
stack S;
int n;
int main() {
    cin >> n;
    cin >> str;
    int cnt = 0;
    for(char c : str) cnt += (c == '(');
    if(cnt * 2 != n) return cout << "No" << endl, 0;//判断是否是左右括号数相同
    for(char c : str) {
        if(!S.empty() && c == ')' && S.top() == '(') S.pop();
        else S.push(c);
    }
    cout << (S.size() <= 2 ? "Yes" : "No") << endl;
}

优化2

栈模拟2

#include 
#include 
#include 
#include 
using namespace std;
const int maxn=2e5+5;
int main(){
    char s[maxn];
    int n;
    while(~scanf("%d",&n)){
        scanf("%s",s);
        stack st;
        int cnt=0;
        int l=0,r=0;
        for(int i=0;i

你可能感兴趣的:(括号匹配---栈的运用)