learning target:
Goal: proficiently use the knowledge learned in Java
Learning Content:
The content of this article: Use Java to achieve bracket matching
Article Directory
Title description:
Given a string s that only includes'(',')','{','}','[',']', judge whether the string is valid.
A valid string must meet:
- The left parenthesis must be closed with the same type of right parenthesis.
- The opening parenthesis 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
Problem-solving ideas:
To solve the problem of bracket matching, you need to use the stack. When the left bracket is encountered, it is pushed into the stack, and when the right bracket is encountered, it is popped, and judge whether the popped element matches the right bracket at this time. If it does not match, it returns false.
- Create stack
- Encountered a left curly brace, push it onto the stack
- Encounter a left bracket, push it onto the stack
- Encounter a left parenthesis, push it onto the stack
-
Encounter a right parenthesis, pop out of the stack, and determine whether the top matches the right parenthesis
-
If we find it matches, we continue to traverse
-
When the right square bracket is encountered, the stack is popped, and the top judges whether it matches the square bracket
-
If we find it matches, we continue to traverse
-
Encounter the right curly brace, pop out of the stack, and determine whether the top matches the curly brace
-
If we find it matches, we continue to traverse
At this point, all traversal is complete, and the stack is empty, so this is a match
Implementation code
- method one:
public static boolean isValid(String s) {
Stack<Character> stack = new Stack<>();//创建栈
//for循环遍历栈
for(int i=0;i<s.length();i++){
char c=s.charAt(i);//获取当前位置元素
//当此时是左括号时,入栈
if(c=='('||c=='{'||c=='['){
stack.push(c);
}
//如果此时不是左括号(是右括号)并且栈为空,说明括号不匹配,则返回false
if(stack.isEmpty()){
return false;
}
//当前元素时右括号
if(c==')'||c==']'||c=='}'){
Character top = stack.pop();
//判断括号是否匹配
if((top=='('&&c!=')')||(top=='['&&c !=']')||(top=='{'&&c!='}')){
return false;
}
}
}
if (stack.isEmpty()) {
return true;
}
return false;
}
- Method Two:
public static boolean isValid(String s) {
Stack<Character> stack = new Stack<>();//创建栈
//for循环遍历栈
for(int i=0;i<s.length();i++){
char c=s.charAt(i);//获取当前元素、
//如果当前元素时左圆括号,则入栈右圆括号
//如果当前元素时左方括号,则入栈右方括号
//如果当前元素时左花括号,则入栈右花括号
if(c=='('){
stack.push(')');
}else if(c=='{'){
stack.push('}');
}else if(c=='['){
stack.push(']');
}else if(stack.isEmpty()||c!=stack.pop()){
//判断是否匹配
return false;
}
}
if(stack.isEmpty()){
return true;
}
return false;
}