Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()" Output: true
Example 2:
Input: "()[]{}" Output: true
给定一个字符串,根据其括号情况是否合法。我们观察字符串,每个左括号都对应一个右括号,且合法的条件是同一组括号中间没有其他未封闭的左或右括号。由此我们很容易想到使用栈来存储括号,遇到左括号时直接压栈,遇到右括号时判断其对应的左括号是否在栈顶,这个过程同时需要判断栈是否为空,如果在栈顶,则弹出在栈顶对应的左括号,否则不和服。遍历整个字符串后,如果栈为空,则说明所有的左右括号都是封闭的。代码记录如下:
class Solution {
public:
bool isValid(string s) {
stack<char> charStack;
for(auto &c : s)
{
switch(c){
case '{':
case '[':
case '(':
charStack.push(c);
break;
case ')':
if(charStack.empty() || charStack.top() != '(')
return false;
else
charStack.pop();
break;
case ']':
if(charStack.empty() || charStack.top() != '[')
return false;
else
charStack.pop();
break;
case '}':
if(charStack.empty() || charStack.top() != '{')
return false;
else
charStack.pop();
break;
default:;
}
}
return charStack.empty();
}
};