20. Valid Parentheses 有效括号
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.
判断一个字符串是否是有效的括号组合
思路,依次将这些字符入栈,判断栈顶元素与当前元素是否是对应上的,是则pop,不是则入栈,到最后判断栈是否为空。
- class Solution {
- public:
- bool isValid(string s) {
- stack<char> result;
- int n=s.size();
- if(n==0) return true;
- for(int i=0;i<n;i++)
- {
- if(result.empty())
- result.push(s[i]);
- else if(result.top()=='('&&s[i]==')'||
- result.top()=='['&&s[i]==']'||
- result.top()=='{'&&s[i]=='}')
- result.pop();
- else
- result.push(s[i]);
-
- }
- return result.empty();
- }
- };
别人的思路:
这种方法能够更快的判断不符合条件的字符串,不需要将字符串遍历完成。
- class Solution {
- public:
- bool isValid(string s) {
- stack<char> paren;
- for (char& c : s) {
- switch (c) {
- case '(':
- case '{':
- case '[': paren.push(c); break;
- case ')': if (paren.empty() || paren.top()!='(') return false; else paren.pop(); break;
- case '}': if (paren.empty() || paren.top()!='{') return false; else paren.pop(); break;
- case ']': if (paren.empty() || paren.top()!='[') return false; else paren.pop(); break;
- default: ;
- }
- }
- return paren.empty() ;
- }
- };
注意:只要当前的字符是)}]三个的一个,如果不能与栈顶结合,那就说明这个字符串是错误的。比如下面的代码。
- <span style="background-color: rgb(255, 255, 255);">class Solution {
- public:
- bool isValid(string s) {
- stack<char> result;
- for(auto & a:s){
- if(a=='(') result.push(')');
- else if(a=='{') result.push('}');
- else if(a=='[') result.push(']');
- else if(result.empty()||result.top()!=a)
- return false;
- else result.pop();
- }
- return result.empty();
- }