[Leetcode] Valid Parentheses

来源:互联网 发布:作业调度算法 编辑:程序博客网 时间:2024/06/05 16:33

题目:

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> record;        for (int i = 0; i < (int)s.size(); ++i) {            if (s[i] == '(' || s[i] == '[' || s[i] == '{') {                record.push(s[i]);            } else {                if (record.empty()) return false;                if (s[i] == ')' && record.top() == '(') record.pop();                else if (s[i] == ']' && record.top() == '[') record.pop();                else if (s[i] == '}' && record.top() == '{') record.pop();                else return false;   //unknown character            }        }        return record.empty();    }};


总结:复杂度O(n).

                                             
0 0