[LeetCode] 20. Valid Parentheses

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

思路是用栈,如果栈顶是(,下一个字符是),就把栈顶的(出栈,[{也是一样,最后看栈是否为空就行了

bool isValid(string s)
{
    stack<char> stk;
    for (char c : s)
    {
        if (stk.empty() || c == '(' || c == '[' || c == '{')
        {
            stk.push(c);
            continue;
        }

        char top = stk.top();
        if ((top == '(' && c == ')') ||
            (top == '[' && c == ']') ||
            (top == '{' && c == '}'))
        {
            stk.pop();
        }
        else
        {
            return false;
        }
    }

    return stk.empty();
}

看了下LeetCode上其他的代码,我觉得我的这个版本挺好的,就不介绍其他代码了,思路都是一样的

posted @ 2018-08-10 15:50  arcsinW  阅读(103)  评论(0编辑  收藏  举报