20. Valid Parentheses*
原创
©著作权归作者所有:来自51CTO博客作者珍妮的选择的原创作品,请联系作者获取转载授权,否则将追究法律责任
20. Valid Parentheses*
https://leetcode.com/problems/valid-parentheses/
题目描述
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:
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
C++ 实现 0
20210322 更新: C++ 实现 1
相对还是写繁琐了, 只需要一个哈希表即可. 另外注意最后要保证栈也要为空才行:
class Solution {
public:
bool isValid(string s) {
stack<char> st;
unordered_map<char, char> record{{'(', ')'},
{'{', '}'},
{'[', ']'}};
for (int i = 0; i < s.size(); ++ i) {
if (record.count(s[i])) st.push(s[i]);
else {
if (st.empty()) return false;
auto c = st.top();
st.pop();
if (record[c] != s[i]) return false;
}
}
return st.empty();
}
};
C++ 实现 1
使用栈. 遇到 left brace 存入 stack 中, 遇到 right brace 判断和 stack.top()
的结果是否匹配.
class Solution {
public:
bool isValid(string s) {
stack<char> st;
unordered_map<char, char> left{{'(', ')'},
{'{', '}'},
{'[', ']'}};
unordered_map<char, char> right{{')', '('},
{'}', '{'},
{']', '['}};
for (int i = 0; i < s.size(); ++ i) {
if (left.count(s[i])) st.push(s[i]);
else {
if (st.empty() || right[s[i]] != st.top()) return false;
st.pop();
}
}
return st.empty();
}
};