码迷,mamicode.com
首页 > 其他好文 > 详细

Valid Parentheses

时间:2014-11-14 21:02:22      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   os   使用   sp   

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.

括号匹配的问题,使用栈解决。(注意,访问栈元素时要先判断栈是否为空)

C++实现代码如下:

#include<iostream>
#include<string>
#include<stack>
using namespace std;

class Solution {
public:
    bool isValid(string s) {
        size_t index=0;
        stack<char> ss;
        while(index<s.length())
        {
            char c;
            switch(s[index])
            {
            case ( :
            case [ :
            case { :
                ss.push(s[index]);
                break;
            case ) :
                if(ss.empty())
                    return false;
                c=ss.top();
                if(c!=()
                    return false;
                ss.pop();
                break;
            case ] :
                if(ss.empty())
                    return false;
                c=ss.top();
                if(c!=[)
                    return false;
                ss.pop();
                break;
            case } :
                if(ss.empty())
                    return false;
                c=ss.top();
                if(c!={)
                    return false;
                ss.pop();
                break;
            default:
                return false;
            }
            index++;
        }
        if(index==s.length()&&ss.empty())
            return true;
        return false;
    }
};

int main()
{
    string str="]";
    Solution s;
    cout<<s.isValid(str)<<endl;
}

运行结果:

bubuko.com,布布扣

Valid Parentheses

标签:style   blog   http   io   color   ar   os   使用   sp   

原文地址:http://www.cnblogs.com/wuchanming/p/4098102.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!