有效的括号(栈)

给定一个只包括 '('')''{''}''['']' 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。
  3. 每个右括号都有一个对应的相同类型的左括号。

 

示例 1:

输入:s = "()"

输出:true

示例 2:

输入:s = "()[]{}"

输出:true

示例 3:

输入:s = "(]"

输出:false

示例 4:

输入:s = "([])"

输出:true

 

class Solution {
public:
    bool isValid(string s) {
        stack<char> st;
        for(char c:s){
            if(c=='('||c=='['||c=='{')
                st.push(c);
            else if(c==')'||c==']'||c=='}'){
                if(st.empty()) return false;
                else{
                    char top = st.top();
                    if((c == ')' && top == '(') || (c == ']' && top == '[') || (c == '}' && top == '{'))
                        st.pop();
                    else return false;
                }
            }
        }
        if(st.empty()) return true;
        return false;
    }
};

 

posted on 2025-01-02 14:05  _月生  阅读(7)  评论(0)    收藏  举报