1. Topic
Given a string s consisting only of '(', ')', '{', '}', '[', ']', determine whether the string is valid.
A valid string must satisfy:
- An opening parenthesis must be closed with a closing parenthesis of the same type.
- Opening parentheses must be closed in the correct order.
- Each closing parenthesis has a corresponding opening parenthesis of the same type.
Example 1:
Input : s = "()"
Output : true
Example 2:
Input : s = "()[]{}"
Output : true
Example 3:
Input : s = "(]"
Output : false
Link to the topic: https://leetcode.cn/problems/valid-parentheses
2. Diagram
Verify the symmetry of the brackets. The brackets are divided into three types: small brackets, square brackets and curly brackets. You can use the first-in-last-out feature of the stack to put all the left brackets ["(", "[", "{"] into the stack first, and then when you encounter a right bracket, let it match with the element on the top of the stack. Whether "(([]))" is legal, the execution process is as follows:
-
When the left parenthesis is encountered first, it is pushed onto the stack first:
-
接下来又是左括号,继续入栈:
然后又是左中括号,继续入栈:
接下来是右中括号,与栈顶元素匹配,“[]”为一对合法的括号,匹配成功栈顶元素出栈:
接下来又是右括号,与栈顶元素匹配,“()”为一对合法的括号,匹配成功栈顶元素出栈:
接下来又是右括号,与栈顶元素匹配,“()”为一对合法的括号,匹配成功栈顶元素出栈:
当字符串循环结束并且栈为空栈时,则证明此字符串的括号匹配合法,最终的效果如下图所示:
3. Java sample code
class Solution {
public boolean isValid(String s) {
//1.特判
if (s.isEmpty()) return true;
//2.创建辅助栈
Stack<Character> stack = new Stack<>();
//3.遍历
for (char c : s.toCharArray()) {
if (c == '(') {
stack.push(')');
} else if (c == '[') {
stack.push(']');
} else if (c == '{') {
stack.push('}');
} else if (stack.isEmpty() || c != stack.pop()) {
return false;
}
}
//4.返回
return stack.isEmpty();
}
}
Results of the: