算法day 30 有效的括号

题目描述

思路:双栈
对于括号的有效匹配,我们可以采用两个栈来实现。我们首先在输入栈中将整个串的元素入栈,随后由于括号的匹配特性,成对的括号中右括号会后入栈,这样的话我们在入栈完整个串之后,开始将右括号弹出并输入到输出栈,待到输入栈的栈顶均为左括号时开始进行两个栈的栈顶匹配,直至输入栈空,最后根据两个栈的状态决定返回值。

代码如下

public:
stack<char> stack_in;
stack<char> stack_out;
bool isValid(string s) {
    for(char ch : s){//将整个串压入输入栈
        stack_in.push(ch);
    }
    while(!stack_in.empty()){
        if(stack_in.top() == ']' || stack_in.top() == '}' || stack_in.top() == ')'){//将右括号弹出输入栈并压入输出栈
               stack_out.push(stack_in.top());
               stack_in.pop();
        }else if(stack_out.empty()){//防止串中没有右括号导致程序陷入死循环
            break;
        }else if(stack_in.top() == '('){
            if(stack_out.top() == ')'){
                stack_in.pop();
                stack_out.pop();
            }else{
                break;
            }
        }else if(stack_in.top() == '['){
            if(stack_out.top() == ']'){
                stack_in.pop();
                stack_out.pop();
        }else{
            break;
        }
    }else if(stack_in.top() == '{'){
            if(stack_out.top() == '}'){
                stack_in.pop();
                stack_out.pop();
       }else{//左右括号不匹配,直接退出
        break;
       }
    }
  }
  return stack_in.empty()&&stack_out.empty()? true:false; 
}

时间复杂度:O(n)
空间复杂度:O(n)

END

posted on 2025-05-16 14:09  sakura430  阅读(16)  评论(0)    收藏  举报