使用stack,使得这个操作变得相当的简单。
package com.java.util;
import java.util.Stack;
public class MyStack {
public static boolean check(String input){
Stack<Character> stack = new Stack<Character>();
for(int i=0;i<input.length();i++){
char ch = input.charAt(i);
switch(ch){
case '{': case '[': case '(':
stack.push(ch);
break;
case '}': case ']': case ')':
if(!stack.isEmpty()){//[]](){}
char chx = stack.pop();
if(ch == '}' && chx != '{'
|| (ch == ']' && chx != '[')
|| (ch == ')' && chx != '(')){
return false;
}
}else{//[](){})
return false;
}
break;
default:
break;
}
}
if(!stack.isEmpty()){//[](){}(
return false;
}
return true;
}
public static void main(String[] args) {
String input = "[wer]()asdf{adsf}";
System.out.println(MyStack.check(input));
}
}