多种括号的匹配 Valid Parentheses

142 篇文章 20 订阅
45 篇文章 0 订阅

题目源自于Leetcode。

题目: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.

思路:由于这里的多种括号,所以不能用原来常用的一个int型来模拟栈的情况。因为这种情况下栈内的内容不只有'('这一种。需要借助完整的栈来做。

STL中的stack:

    下面解法使用了STL中的stack容器。stack是一种适配器(adapter)类,默认的底层实现为顺序容器vector。

stack的声明方法:stack<int> st;

stack的基本操作有:

压入栈stack.push(i)。

弹出栈stack.pop()。  注意,pop()是没有返回值的。所以想取得栈顶的话,需要先top再pop。

返回栈的当前元素个数stack.size()。

返回当前栈顶元素stack.top()。 注意调用它之前最好先判断栈是否为空

当前栈是否为空stack.empty()。 


题目解答:

class Solution {
public:
    bool isValid(string s) {
        stack<int> st;
        int n = s.length();
        int i;
        for(i=0;i<n;i++)
        {
            switch(s[i])
            {
                case '(': st.push(1); break;
                case '[': st.push(2); break;
                case '{': st.push(3); break;
                
                case ')': if(st.empty() || st.top() != 1) return false;  st.pop(); break;
                case ']': if(st.empty() || st.top() != 2) return false;  st.pop(); break;
                case '}': if(st.empty() || st.top() != 3) return false;  st.pop(); break;
            }
        }
        if(st.size() == 0)
            return true;
        else
            return false;
        
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值