Valid Parentheses

Leetcode 20. Valid Parentheses

Description:

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

在很多数据结构书中都提到的括号匹配问题,是栈的典型应用,代码如下:

class Solution {

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

};

参考Discuss中头名代码后,他的思路是当遇到括号左半部分,将右半部分压栈,这样当遇到右半部分直接与栈顶值比较就可,这样在分类时不需要针对左半部分区别右半部分的具体形式,只需要自己跟自己比较是否相等,代码简洁程度大大提高。

修改后如下:

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

注意:if (st.empty() || c != st.top())中两个判断条件的顺序不能错,因为当第一个括号不符合时,先判断c != st.top()会出错,因为st.top()没东西。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值