【LeetCode算法练习(C++)】Valid Parentheses

来源:互联网 发布:python向ssh输入ctrl c 编辑:程序博客网 时间:2024/05/16 09:45

题目:
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.

链接:Valid Parentheses
解法:遍历字符串,左括号入栈,右括号检查栈顶元素,若不对应立即返回失败。时间O(n)

class Solution {public:    bool isValid(string s) {        stack<char> st;        int len = s.length();        for (int i = 0; i < len; i++) {            if (s[i] == '(' || s[i] == '[' || s[i] == '{') {                st.push(s[i]);            } else if (!st.empty() && s[i] == ')') {                if (st.top() == '(') st.pop();                else return false;            } else if (!st.empty() && s[i] == ']') {                if (st.top() == '[') st.pop();                else return false;            } else if (!st.empty() && s[i] == '}') {                if (st.top() == '{') st.pop();                else return false;            } else {                return false;            }        }        return st.empty();    }};

Runtime: 3 ms

原创粉丝点击