欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

合法括号序列判断——利用栈的特性

程序员文章站 2024-03-18 22:25:04
...

题目链接
合法括号序列判断——利用栈的特性

class Parenthesis {
public:
    bool chkParenthesis(string A, int n) {
        // write code here
       stack<char> st;
        for(int i=0;i<A.length();i++){
            if(A[i]!='(' &&  A[i]!=')') return false;
            else{
                if(A[i]=='(')st.push(A[i]);
                if(A[i]==')'){
                    if(st.empty()) return false;
                    else st.pop();
                }
            }
        }
        if(!st.empty()) return false;
        return true;
    }
};
#include<bits/stdc++.h>
using namespace std;
int main(){
	
        string A;
		int n;
        // write code here
        stack<char> st;
        for(int i=0;i<A.length();i++){
            if(A[i]!='(' &&  A[i]!=')') return false;
            else{
                if(A[i]=='(')st.push(A[i]);
                if(A[i]==')'){
                    if(st.empty()) return false;
                    else st.pop();
                }
            }
        }
        if(!st.empty()) return false;
        return true;
}

相关标签: OJ刷题