【8】20. Valid Parentheses

本文介绍了一种使用栈数据结构来验证括号字符串是否有效的算法。该算法通过遍历输入字符串,利用栈来匹配和验证每一对括号,确保它们正确闭合。文章提供了详细的C++实现代码。

20. Valid Parentheses

  • Total Accepted: 167254
  • Total Submissions: 517330
  • Difficulty: Easy
  • Contributors: Admin

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.

Solution:

Use stack. When we meet a left parentheses, we push it into the stack. When we meet a right parentheses, we will return false if the stack is empty, otherwise, we will pop the top of the stack to find if it is the corresponding left parentheses.

 1 class Solution {
 2 public:
 3     bool isValid(string s) {
 4         stack<char> st;
 5         for(int i = 0; i < s.size(); i++){
 6             if(s[i] == '(' || s[i] == '{' || s[i] == '['){
 7                 st.push(s[i]);
 8             }else if(s[i] == ')' || s[i] == '}' || s[i] == ']'){
 9                 if(st.empty()){
10                     return false;
11                 }else{//只需判断false的情况,最后再pop就可以了
12                     if(s[i] == ')' && st.top() != '(') return false;
13                     if(s[i] == ']' && st.top() != '[') return false;
14                     if(s[i] == '}' && st.top() != '{') return false;
15                     st.pop();
16                 }
17             }
18         }
19         //return true;此时不能直接return true,因为stack里可能会有剩余的左括号
20         return st.empty();
21     }
22 };

 

 

 

 

 

 

转载于:https://www.cnblogs.com/93scarlett/p/6362009.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值