增加bracketMatching方法
/**
*
* Is the bracket matching?
*
* @param paraString
* The given expression.
* @return Match or not.
*
*/
public static boolean bracketMatching(String paraString){
//Step 1. Initialize the stack through pushing a '#' at the bottom.
CharStack tempStack = new CharStack();
tempStack.push('#');
char tempChar, tempPopedChar;
//Step 2. Process the string. For a string, length() is a method
//instead of a member variable.
for (int i = 0; i < paraString.length(); i++){
tempChar = paraString.charAt(i);
//调用一个方法,来找出第i点的字符
switch (tempChar){
case '(':
case '[':
case '{':
//这三个case中任意一个成立,都会进入相同的管道,并且若不break,会继续进行后文的pop操作
tempStack.push(tempChar);
break;
case ')':
tempPopedChar = tempStack.pop();
if (tempPopedChar != '('){
return false;
//如果上一个输入且未抵消的并非(,则判断为错误
}//Of if
break;
case ']':
tempPopedChar = tempStack.pop();
if (tempPopedChar != '['){
return false;
}//Of if
break;
case '}':
tempPopedChar = tempStack.pop();
if (tempPopedChar != '{'){
return false;
}//Of if
break;
default:
//Do nothing
}//Of switch
}//Of for
tempPopedChar = tempStack.pop();
if (tempPopedChar != '#'){
return false;
}//Of if
return true;
}//Of bracketMatching
/**
*
* The entrance of the program.
*
* @param args
* Not used now.
*
*/
public static void main(String args[]) {
CharStack tempStack = new CharStack();
for (char ch = 'a'; ch < 'm'; ch++) {
tempStack.push(ch);
System.out.println("The current stack is: " + tempStack);
}// Of for i
char tempChar;
for (int i = 0; i < 12; i++) {
tempChar = tempStack.pop();
System.out.println("Poped:" + tempChar);
System.out.println("The current stack is: " + tempStack);
}// Of for i
boolean tempMatch;
String tempExpression = "[2 + (1 - 3 )] * 4";
tempMatch = bracketMatching(tempExpression);
System.out.println("Is the expression " + tempExpression + " bracket matching?" + tempMatch);
tempExpression = "( ) )";
tempMatch = bracketMatching(tempExpression);
System.out.println("Is the expression " + tempExpression + " bracket matching?" + tempMatch);
tempExpression = "()()(())";
tempMatch = bracketMatching(tempExpression);
System.out.println("Is the expression " + tempExpression + " bracket matching?" + tempMatch);
tempExpression = "({}[])";
tempMatch = bracketMatching(tempExpression);
System.out.println("Is the expression " + tempExpression + " bracket matching?" + tempMatch);
tempExpression = ")(";
tempMatch = bracketMatching(tempExpression);
System.out.println("Is the expression " + tempExpression + " bracket matching?" + tempMatch);
}// Of main