第 15 天: 栈的应用(括号匹配)
任务描述: 检查一个字符串的括号是否匹配. 所谓匹配, 是指每个左括号有相应的一个右括号与之对应, 且左括号不可以出现在右括号右边. 可以修改测试字符串, 检查不同情况下的运行.
15.1 仅在昨天的代码基础上增加了一个 bracketMatching 方法, 以及 main 中的相应调拭语句.
15.2 操作系统的核心数据结构. 对于计算机而言, 如何降低时间、空间复杂度才是王道.
15.3 除了关注的括号, 其它字符不起任何作用.
15.4 一旦发现不匹配, 就直接返回, 不用罗嗦.
/**
* 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, tempPoppedChar;
// 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);
switch (tempChar) {
case '(':
case '[':
case '{':
tempStack.push(tempChar);
break;
case ')':
tempPoppedChar = tempStack.pop();
if (tempPoppedChar != '(') {
return false;
}// Of if
break;
case ']':
tempPoppedChar = tempStack.pop();
if (tempPoppedChar != '[') {
return false;
}// Of if
break;
case '}':
tempPoppedChar = tempStack.pop();
if (tempPoppedChar != '{') {
return false;
}// Of if
break;
default:
// Do nothing
}// Of switch
}// Of for
tempPoppedChar = tempStack.pop();
if (tempPoppedChar != '#') {
return false;
} // Of if
return true;
}// Of bracketMatching
package datastructures.stack;
/**
* ClassName: CharStackTest
* Package: datastructures.stack
* Description:
*
* @Author: luv_x_c
* @Create: 2023/4/19 22:31
*/
public class CharStackTest {
/**
* ********************
* The entrance of the program.
*
* @param args Not used now.
* ********************
*/
public static void main(String args[]) {
CharStack tempStack = new CharStack();
boolean tempMatch;
String tempExpression = "[2 + (1 - 3)] * 4";
tempMatch = tempStack.bracketMatching(tempExpression);
System.out.println("Is the expression " + tempExpression + " bracket matching? " + tempMatch);
tempExpression = "( ) )";
tempMatch = tempStack.bracketMatching(tempExpression);
System.out.println("Is the expression " + tempExpression + " bracket matching? " + tempMatch);
tempExpression = "()()(())";
tempMatch = tempStack.bracketMatching(tempExpression);
System.out.println("Is the expression " + tempExpression + " bracket matching? " + tempMatch);
tempExpression = "({}[])";
tempMatch = tempStack.bracketMatching(tempExpression);
System.out.println("Is the expression " + tempExpression + " bracket matching? " + tempMatch);
tempExpression = ")(";
tempMatch = tempStack.bracketMatching(tempExpression);
System.out.println("Is the expression " + tempExpression + " bracket matching? " + tempMatch);
}// Of main
}
一开始写的没有考虑到只有左括号的情况,少写了最后判断栈底#的几句,测试了几下发现了问题