leetcode(20):Valid Parentheses

在这里插入图片描述

题目

给定一个字符串,只包含’(‘, ‘)’, ‘{‘, ‘}’, ‘[’ 和’]’这些字符,检查它是否是“有效”的。
括号必须以正确的顺序关闭,例如”()” 和”()[]{}”都是有效的,”(]” 和”([)]”是无效的。

分析:
本题考查的是栈结构,具有后进先出的特性。有效包含2个方面,第一个是如果是关闭的括号,前一位一定要刚好有一个开启的括号;第二个是最终结果,需要把所有开启的括号都抵消完。一个比较容易出错的地方是,遇到关闭括号时,要先判断栈是否已经空了。

  1. Valid Parentheses

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

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.

Example 1:

Input: “()”
Output: true
Example 2:

Input: “()[]{}”
Output: true
Example 3:

Input: “(]”
Output: false
Example 4:

Input: “([)]”
Output: false
Example 5:

Input: “{[]}”
Output: true

代码

class Solution {
public:
    bool isValid(string s) {
        int s_length=(int)s.length();
        std::stack<char> left_char_stack;
        for(int i=0;i<s_length;i++) {
            if( (s[i]=='(') || (s[i]=='[') || (s[i]=='{') ){
                left_char_stack.push(s[i]);
            }else{
                if(left_char_stack.empty())
                    return false;
                char tmp= left_char_stack.top();
                if( (tmp=='('&&s[i]==')') || (tmp=='['&&s[i]==']') || (tmp=='{'&&s[i]=='}') ){
                    left_char_stack.pop();
                }else{
                    return false;
                }
            }
        }
        if(left_char_stack.empty())
            return true;
        else
            return false;
    }


};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值