20. Valid Parentheses

来源:互联网 发布:ps绘画软件 编辑:程序博客网 时间:2024/04/30 23:25

题目描述:

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.

https://leetcode.com/problems/valid-parentheses/description/


思路分析:检验括号是否是匹配的,我们使用一个栈来解决。有三种错误情况:字符串为空;右括号匹配错误(不同符号或匹配空栈);左括号没有匹配。

所以我们的算法思路就是先判断字符串长度,然后开始入栈,如果为“(”、“[”和“{”等左括号的话就进栈,然后看下一个字符是否匹配,不匹配就返回false,匹配就出栈。最后检查所有元素是否出栈。


代码:

class Solution {public:    bool isValid(string s) {        stack<char> stk;        if(s.length()%2 != 0)//odd number of chars can not be valid            return false;        for(int i = 0; i < s.length(); i++){            if(s[i] == '(' || s[i] == '[' || s[i] == '{')                stk.push(s[i]);            if(s[i] == ')' && (stk.empty() || stk.top() != '('))//false circumstances                return false;            if(s[i] == ']' && (stk.empty() || stk.top() != '['))                return false;            if(s[i] == '}' && (stk.empty() || stk.top() != '{'))                return false;            if(s[i] == ')' && stk.top() == '(')//valid circumstance                stk.pop();            if(s[i] == ']' && stk.top() == '[')                stk.pop();            if(s[i] == '}' && stk.top() == '{')                stk.pop();        }         return stk.empty();// the stack is empty means validness.    }};
时间复杂度:O(n) //n为字符串长度


反思:做的时候很没有思路,错了无数遍,希望以后做题把所有情况都考虑完整的,不要多次submit。开始的判断奇数其实没有必要,提升了一丢丢性能罢了。