/**
* 基于栈实现--括号匹配算法
*/
public class BracketMarch {
ArrayStack<Character> stack = new ArrayStack<Character>();
public boolean isValid(String s) {
for (int i = 0; i < s.length(); i++) {//[(]{)}
char c = s.charAt(i);
if(c == '{' || c == '[' || c == '(') {//将字符串中的所有左括号入栈
stack.push(c);
} else {
if(stack.isEmpty()) {
return false;
}
char topChar = stack.pop();
if(topChar == '{' && c != '}') {
return false;
}
if(topChar == '[' && c != ']') {
return false;
}
if(topChar == '(' && c != ')') {
return false;
}
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
System.out.println(new BracketMarch().isValid("[]{}()"));
System.out.println(new BracketMarch().isValid("[(]{)}"));
}
}
结果:
true
false
玩转数据结构(十二)括号匹配算法
最新推荐文章于 2023-10-15 19:49:23 发布