LeetCode20. Valid Parentheses

17 篇文章 0 订阅
9 篇文章 0 订阅

LeetCode20. Valid Parentheses

原题地址

题目描述

 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.

思路

这题我是直接看的网上的题解,感觉该博主第二种思路非常好,简单描述一下。
就是遍历输入的字符串中的字符,如果遇到’(‘就将’)’push入栈,遇到’[‘就将’]’push入栈,遇到’{‘就将’}’push入栈;如果栈为空或者字符串当前字符不等于栈顶元素就说明该字符串不满足条件,如果当前字符串中的字符和栈顶字符相同,就将栈顶元素pop出;最后看栈是不是为空。

代码实现

    class Solution {
public:
    bool isValid(string s) {
        int len = s.length();  
        if(len==0) return true;  
        if(len%2) return false;  
        stack<char> sk;  
        for(int i = 0; i < len; i++)  
        {  
            if(s[i] == '(') sk.push(')');  
            else if(s[i] == '{') sk.push('}');  
            else if(s[i] == '[') sk.push(']');  
            else if(sk.empty() || sk.top() != s[i]) return false;  
            else sk.pop();  
        }  
        return sk.empty(); 
    }
};

鸡汤

好几天没写博客了,感觉最近状态不是很好,及时调整,继续坚持!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值