LeetCode 19 Valid Parentheses

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过!!!

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