LeetCode #20. Valid Parentheses

本文详细解析了LeetCode第20题“Valid Parentheses”的解决方案,通过使用栈和映射表,验证括号字符串的有效性。文章阐述了算法思路,提供了C++实现代码,适合算法初学者和面试准备者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode #20. Valid Parentheses

题目描述

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

An input string is valid if:

1.Open brackets must be closed by the same type of brackets.
2.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

##思路
主要利用了栈的思想,并给( ){ } [ ] 这六个字符分别赋值为1、-1、2、-2、3、-3。从字符串的第一个字符开始往后遍历:
(1)如果遇到正数就压进栈里;
(2)如果出现负数,则看栈是否为空:
如果为空,则返回false;
如果不为空,则看栈顶数字是否为该数字的相反数,如果不是则返回false,如果是则将栈顶元素抛出,接着看字符串中的下一个字符。

这里要注意:
1.如果字符串的第一个字符对应的数字为负数,则可以直接返回false;
2.当字符串遍历完以后,如果栈不为空,则返回false,为空才返回true。

##代码

class Solution {
public:
    bool isValid(string s) {
        stack<int>ss;
        map<char,int>m;
        m.clear();
        m['('] = 1;
        m[')'] = -1;
        m['{'] = 2;
        m['}'] = -2;
        m['['] = 3;
        m[']'] = -3;
        while(!ss.empty()) {
            ss.pop();
        }
        int i, j;
        if(m[s[0]]<0) {
            return false;
        }
        for(i=0; i<s.length(); i++) {
            j = m[s[i]];
            if(j>0) {
                ss.push(j);
            }
            else {
                if(ss.empty()) {
                    return false;
                }
                if(-1*j != ss.top()) {
                    return false;
                }
                else {
                    ss.pop();
                }
            }
        }
        if(ss.empty()) {
            return true;
        }
        return false;


    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值