Valid Parentheses
Description:
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
Example 3:
Input: "(]" Output: false
Example 4:
Input: "([)]" Output: false
Example 5:
Input: "{[]}" Output: true
bool isValid(string s)
{
stack<char> parentheses; // 定义一个栈
for (int i = 0; i < s.size(); ++i)
{
if (s[i] == '(' || s[i] == '[' || s[i] == '{') parentheses.push(s[i]); // 如果是左括号 入栈
else
{
if (parentheses.empty()) return false; // 如果为空 返回false
if (s[i] == ')' && parentheses.top() != '(') return false; // 有括号与站定匹配 不匹配返回false
if (s[i] == ']' && parentheses.top() != '[') return false;
if (s[i] == '}' && parentheses.top() != '{') return false;
parentheses.pop();
}
}
return parentheses.empty(); // 若栈为空则为true
}