题目描述(Easy)
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.
题目链接
https://leetcode.com/problems/valid-parentheses/description/
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
算法分析
遇见左括号则入栈,遇见右括号则与栈顶比较是否为一对,并出栈。
提交代码:
class Solution {
public:
bool isValid(string s) {
string left = "([{";
string right = ")]}";
stack<char> sta;
for(auto c : s)
{
if(left.find(c) != string::npos)
sta.push(c);
else
{
if(sta.empty() || sta.top() != left[right.find(c)])
return false;
sta.pop();
}
}
return sta.empty();
}
};