* 将左括号进栈,如果碰到右括号就退栈
*注意:bracketMap 右括号为key,左括号为value方便查找对应的括号
源码如下:
public class BracketCupling {
public static void main(String[] args){
System.out.println(isMatch("(***)-[{-------}]")); //true
System.out.println(isMatch("(2+4)*a[5]")); //true
System.out.println(isMatch("({}[]]])")); //false
System.out.println(isMatch("())))")); //false
}
public static boolean isMatch(String s) {
Map<Character,Character> bracket = new HashMap<>();
bracket.put('}','{');
bracket.put(']','[');
bracket.put(')','(');
Stack stack = new Stack();
for (int i = 0; i <s.length() ; i++) {
Character tempCh = s.charAt(i);
if(bracket.containsValue(tempCh)) {
stack.push(tempCh);
} else if(bracket.containsKey(tempCh)) {
if(stack.empty()) {
return false;
}
if (stack.peek()==bracket.get(tempCh)) {
stack.pop();
}else {
return false;
}
}
}
return stack.empty()?true:false;
}
}
打开App,阅读手记