title: Daily Practice (36): Valid Parentheses
categories:[Swords offer]
tags:[Daily practice]
date: 2022/03/15
Exercise of the Day (36): Effective Brackets
Given a string s containing only '(', ')', '{', '}', '[', ']', determine whether the string is valid.
A valid string must satisfy:
Opening parentheses must be closed with closing parentheses of the same type.
Left parentheses must be closed in the correct order.
Example 1:
Input: s = "()"
output: true
Example 2:
Input: s = "()[]{}"
output: true
Example 3:
Input: s = "(]"
output: false
Example 4:
Input: s = "([)]"
output: false
Example 5:
Input: s = "{[]}"
output: true
hint:
1 <= s.length <= 104
s consists only of parentheses '()[]{}'
Source: LeetCode
Links: https://leetcode-cn.com/problems/valid-parentheses
Method 1: stack + hash table
Thought analysis
- The length of a valid bracket string, must be an even number!
- Before the closing parenthesis, it must be the corresponding opening parenthesis to cancel!
- Before the right parenthesis, it is not the corresponding left parenthesis, then the string must not be a valid parenthesis!
bool isValid(string s) {
if (s.size() % 2) {
return false;
}
unordered_map<char, char> pairs = {
{')', '('},
{']', '['},
{'}', '{'}
};
stack<char> stk;
for (char ch : s) {
if (pairs.count(ch)) {
if (stk.empty() || stk.top() != pairs[ch]) {
return false;
}
stk.pop();
} else {
stk.push(ch);
}
}
return stk.empty();
}
Method 2: Stack
bool isValid(string s) {
if (s.size() % 2) {
return false;
}
stack<char> st;
for (auto ss : s) {
if (ss == '(') {
st.push(')');
} else if (ss == '[') {
st.push(']');
} else if (ss == '{') {
st.push('}');
} else {
if (st.empty() || st.top() != ss) {
return false;
} else {
st.pop();
}
}
}
return st.empty();
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。