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:

  1. Open brackets must be closed by the same type of brackets.
  2. 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

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();
}
};