[leetcode] 20. Valid Parentheses

来源:互联网 发布:jquery封装json 编辑:程序博客网 时间:2024/06/07 00:10

Question:

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.

Solution:

利用栈的特性,对于合法的括号,右括号的出现则要检查栈顶是否为对应的左括号,是则将栈顶元素弹出,继续检查下一个括号。这样做就能检查一对括号中夹着若干对其他括号,从最里面的一对括号开始检查。若最后栈为空,则说明所有括号均是合法的。
时间复杂度:O(n)
空间复杂度:O(n)

class Solution {public:    bool isValid(string s) {        stack<char> st;        for (int i = 0; i < s.size(); i++) {            if (st.empty()) {                st.push(s[i]);            } else if (s[i] == ']' && st.top() == '[') {                st.pop();            } else if (s[i] == ')' && st.top() == '(') {                st.pop();            } else if (s[i] == '}' && st.top() == '{') {                st.pop();            } else {                st.push(s[i]);            }        }         if (st.empty())            return true;        return false;    }};
原创粉丝点击