凌云的博客

成功=工作+游戏+少说空话

LeetCode 算法题 20. Valid Parentheses

分类:algorithm| 发布时间:2016-07-04 23:59:00


题目

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.

题意

判断括号是否合法。

解法

class Solution {
public:
    bool isValid(string s) {
        stack<char> expect;
        for (char c: s) {
            switch (c) {
                case '(':
                    expect.push(')');
                    break;
                case '{':
                    expect.push('}');
                    break;
                case '[':
                    expect.push(']');
                    break;
                case ')':
                case ']':
                case '}':
                    if (expect.empty() || expect.top() != c) {
                        return false;
                    }

                    expect.pop();
                    break;
                default:
                    return false;
            }
        }

        return expect.empty();
    }
};