Valid Parentheses

LeetCode原题: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.


主要内容:判断给定string类字符串是否合法(三种类型的括号匹配)


解题思想:通过C++里面顺序容器中的stack栈结构实现。扫描string类字符串,判断每个字符,如果该字符属于左括号类型,则压入栈,如果不是则弹出栈顶,如果最后栈为空,则匹配成功,但是如果在该过程中弹出的栈顶与该非左括号类型字符不能完成括号匹配或者出现栈为空的情况,则匹配失败。


参考C++代码:

#include<stack>
class Solution {
public:
    bool isLeft(char c) {
        return (c == '(' || c == '{' || c == '[');
    }
    bool isMatch(char r, char l) {
        if (l == '(') {
            return (r == ')');
        } else
        if (l == '{') {
            return (r == '}');
        } else
        if (l == '[') {
            return (r == ']');
        } else {
            return false;
        }
    }
    bool isValid(string s) {
        stack<char> sc;
        int z = s.size();
        for (int i = 0; i < z; i++) {
            if (isLeft(s[i])) {
                sc.push(s[i]);
            } else {
                if(sc.empty() || !isMatch(s[i], sc.top())) {
                    return  false;
                }
                sc.pop();
            }
        }
        if(!sc.empty()) {
            return false;
        } else
        return true;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值