LeetCode (20)Valid Parentheses

31 篇文章 0 订阅

(20)Valid Parentheses

题目:判断一个字符串是否符合括号使用规则,字符串里有”()”,”[]”,”{}”三种。

例子:”()”和”({}[])”都是正确的,但是”([)”,”({)[}]”都是错误的。

想过之后,觉得直接用栈就可以实现整个字符串的查找,从头搜索,如果搜到的符号是左符号,那么就压入栈中,如果是右符号,那么如果栈是空,那么就直接返回错误,如果不是的话,栈顶必须是次符号的左符号,不然也是错误的,如果是对的那就出栈,最后如果栈是空的,那么就是对的,不是空就证明未闭合,是错误的。

下面是代码:

class Solution {
public:
    bool isValid(string s) {
        stack<string> str_c;
        int len = s.size();
        int i = 0;
        for (i = 0; i < len; i++){
            string str = s.substr(i, 1);
            if(str.compare("(") == 0 || str.compare("[") == 0 || str.compare("{") == 0){
                str_c.push(str);
            }
            else if(str.compare("}") == 0 && !str_c.empty()){
                if(str_c.top().compare("{") == 0){
                    str_c.pop();
                }
                else{
                    return false;
                }
            }
            else if(str.compare("]") == 0 && !str_c.empty()){
                if(str_c.top().compare("[") == 0){
                    str_c.pop();
                }
                else{
                    return false;
                }
            }
            else if(str.compare(")") == 0 && !str_c.empty()){
                if(str_c.top().compare("(") == 0){
                    str_c.pop();
                }
                else{
                    return false;
                }
            }
            else{
                return false;
            }
        }
        if(str_c.empty()){
            return true;
        }
        return false;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值