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.

[解题思路]

经典括号匹配问题,使用栈模拟即可

 1 bool Solution::isValid(std::string s)
 2 {
 3     std::stack<char> tmp;
 4     for (int i = 0; i < s.length(); i ++){
 5         if (s[i] == '(' || s[i] == '[' || s[i] == '{')
 6             tmp.push(s[i]);
 7         else if (s[i] == ')'){
 8             if (tmp.size() > 0 && tmp.top() == '(')
 9                 tmp.pop();
10             else
11                 return false;
12         }
13          else if (s[i] == ']'){
14             if (tmp.size() > 0 && tmp.top() == '[')
15                 tmp.pop();
16             else
17                 return false;
18         }
19          else if (s[i] == '}'){
20             if (tmp.size() > 0 && tmp.top() == '{')
21                 tmp.pop();
22             else
23                 return false;
24         }
25     }
26     return tmp.size() == 0;
27 }

 

转载于:https://www.cnblogs.com/taizy/p/3911276.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值