题目描述:一个字符串中包含圆括号()、中括号[ ]、大括号{ },其嵌套的顺序随意。即()(){({})([])}是有效的,([)(]){]}是无效的。验证括号是否匹配的方法就是用“期待的急迫程度”这个概念来解决。关于“期待的急迫程度”概览大家自己晚上查阅了解。
package neteaseprograme;
import java.util.Stack;
public class CheckBracketAvailability {
public static void main(String[] args){
String str = "()(){({})([])}";
char[] bracketChar = str.toCharArray();
Stack<Character> stack = new Stack<Character>();
stack.push(bracketChar[0]);
for (int i = 1; i < bracketChar.length; i++) {
char temp = bracketChar[i];
if(stack.isEmpty()){
stack.push(temp);
}else{
if(stack.peek() == temp-1 || stack.peek() == temp-2){
stack.pop();
}else{
stack.push(temp);
}
}
}
if(stack.isEmpty()){
System.out.println("有效字符串");
}else{
System.out.println("无效字符串");
}
}
}