LeetCode 20 有效括号

LeetCode 20 有效括号

https://leetcode.cn/problems/valid-parentheses/description/

经典括号匹配问题,一眼用栈

class Solution
{
public:
    bool isValid(string s)
    {
        stack<int> st;
        for (int i = 0; i < s.size(); i++) {
            if (s[i] == '(' || s[i] == '[' || s[i] == '{')
                st.push(i);
            else {
                if (st.size() == 0)
                    return false;
                int index = st.top();
                if (s[i] == '}' && s[index] != '{' || s[i] == ']' && s[index] != '[' || s[i] == ')' && s[index] != '(')
                    return false;
                st.pop();
            }
            
        }
    
        return st.size() == 0;
    }
};
none
最后修改于:2024年02月10日 21:29

评论已关闭