Valid Parentheses

每日算法——leetcode系列


问题 Valid Parentheses

Difficulty: Easy

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) {

    }
};

翻译

验证括符的有效性

难度系数:简单

给定一个只包含字符 '(' ')''{''}''['']',判定输入的字符串是否有效。

反括号的位置必须正确, "()""()[]{}" 是有效的, 但 "(]""([)]" 不是有效的。

思路

如果做过用栈实现加减法乘除,这题就简单了
括号都分括号和反括号,假设用左表示“([{”,右表示“)]}”区分
遍历字符串,判断字符在左边还是右边:

  • 如果在左边,直接压栈,
  • 如有在右边,再分两种情况
    1. 如果他和栈顶的字符形成一对括符,表示匹配,弹出栈顶再进行下一个字符判断
    2. 不匹配则不能形成完整的括符,结束

代码

class Solution {
public:
    bool isValid(string s) {
        string left = "([{";
        string right = ")]}";
        stack<char> charStack;
        for (auto ch : s){
            if (left.find(ch) != string::npos){
                charStack.push(ch);
            }else{
                if (charStack.empty()){
                    return false;
                }
                if (charStack.top() != left[right.find(ch)]){
                    return false;
                }
                charStack.pop();
            }
        }
        return charStack.empty();
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值