首页 > 其他 > 详细

Valid Parentheses

时间:2015-03-11 17:00:46      阅读:238      评论:0      收藏:0      [点我收藏+]

题目描述:

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.

  典型的用stack解决的问题。

solution:

bool isValid(string s) {
    if (s.empty() || s.size() % 2 != 0)
        return false;
    stack<char> stk;
    for (int i = 0;i < s.size();++i)
    {
        if(s[i] == ( || s[i] == [ || s[i] == {)
            stk.push(s[i]);
        else
        {
            if (stk.empty())
                return false;
            char ch = stk.top();
            stk.pop();
            if(s[i] == ) && ch != ()
                return false;
            if (s[i] == ] && ch != [)
                return false;
            if (s[i] == } && ch != {)
                return false;
        }
    }
    return stk.empty();
}

  如有其它解法,欢迎来稿。

Valid Parentheses

原文:http://www.cnblogs.com/gattaca/p/4330010.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!