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

LeetCode 19 Valid Parentheses

时间:2015-05-10 15:35:12      阅读:109      评论: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.

见了n次的括号匹配,难度不大,主要使用栈来进行匹配测试,但是记得检测一些边缘的情况,例如一个[,或者一个]时,怎么判断,怎么处理?

class Solution {
public:
    bool isValid(string s) 
{
    stack<char> stk;
    int nSize = s.size();

    for(int i = 0; i!= nSize; ++i)
    {
        if(s[i] == { || s[i] == ( || s[i]== [)
        {
            stk.push(s[i]);
        }
        else
        {
            if(stk.empty())
            {
                return false;
            }
            char cElem = stk.top();
            if(cElem - s[i] ==-1 || cElem - s[i] == -2)
            {
                stk.pop();
                continue;
            }
            else
            {
                return false;
            }
        }
    }
    if(!stk.empty())
    {
        return false;
    }
    return true;
}
};

希望下次见到,还是能一次性AC过!!!

LeetCode 19 Valid Parentheses

标签:

原文地址:http://www.cnblogs.com/bestwangjie/p/4492238.html

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