/*
20. Valid Parentheses My Submissions QuestionEditorial Solution
Total Accepted: 103991 Total Submissions: 355405 Difficulty: Easy
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.
Subscribe to see which companies asked this question
*/
/*
解题思路:
这题就是栈的基本应用。
策略只有一点:遇到左括号入,遇到右括号出并比较。
注意点:在返回的时候如果正确应该栈为空,所以返回的是栈的空判断。
*/
class Solution {
public:
bool isValid(string s) {
//此题是栈的基本应用的一个实例
stack<char> _stack;
if(s.empty())return true;
for(int i=0;i<s.size();i++){
char c=s[i];
//若果是左元素就入栈
if(c=='('||c=='['||c=='{'){
_stack.push(c);
}else{
//在取之前先判断是否为空
if(_stack.empty())return false;
int tmp=_stack.top();
_stack.pop();
switch(c){
case ')': if(tmp!='(') return false;break;
case ']': if(tmp!='[') return false;break;
case '}': if(tmp!='{') return false;break;
}
}
}
return _stack.empty();
}
};