JAVA学习—栈的应用(括号匹配)—2021-06-03
任务描述: 检查一个字符串的括号是否匹配. 所谓匹配, 是指每个左括号有相应的一个右括号与之对应, 且左括号不可以出现在右括号右边. 可以修改测试字符串, 检查不同情况下的运行.
- 仅在昨天的代码基础上增加了一个 bracketMatching 方法, 以及 main 中的相应调拭语句.
- 操作系统的核心数据结构.对于计算机而言, 如何降低时间、空间复杂度才是王道.
- 除了关注的括号, 其它字符不起任何作用.
- 一旦发现不匹配, 就直接返回,不用罗嗦.
————————————————
learn from @minfanphd 原文
在对元素依次进栈过程中,过程可以描述为:
遇到左括号,左括号进栈
遇到右括号,对比栈顶是否为对应的左括号
栈顶为空:输入不合法
栈顶为对应的左括号:左括号出栈
栈顶为非对应的左括号:输入不合法
代码
package a13;
/**
* ********************
* Char stack. Do not use Stack because it's already defined in Java.
* @author hengyuzuo
* ********************
*/
public class CharStack {
/**
* *************
* The depth
* *************
*/
public static final int MAX_DEPTH = 10;
/**
* *************
* The actual depth
* *************
*/
int depth;
/**
* *************
* The data;
* *************
*/
char[] data;
/**
* *************
* Construct an empty sequential list.
* *************
*/
public CharStack() {
depth = 0;
data = new char[MAX_DEPTH];
}// Of the first constructor
/**
* *************
* Overrides the method claimed in Object, the superclass of any class.
* *************
*/
public String toString() {
String resultString = "";
for (int i = 0; i < depth; i++) {
resultString += data[i];
}// Of for i
return resultString;
}// Of toSting
/**
* *************************
* Push an element.
* @param paraChar the given char.
* @return Success or not.
* *************************
*/
public boolean push(char paraChar) {
if (depth == MAX_DEPTH) {
System.out.println("Stack full.");
return false;
}//Of if
data[depth] = paraChar;
depth++;
return true;
}// Of push
/**
* *************************
* Pop an element.
* @param paraChar the given char.
* @return Success or not.
* *************************
*/
public char pop() {
if (depth == 0) {
System.out.println("Nothin to pop.");
return '\0';
}// Of pop
char resultChar = data[depth -1];
depth--;
return resultChar;
}// Of pop
/**
* **************************
* 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 < 11; i++) { tempChar = tempStack.pop();
* System.out.println("Poped: " + tempChar);
* System.out.println("The current stack is: " +tempStack);} }// Of for i
*/
/**
* ************************
* 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);
switch (tempChar) {
case '(':
case '[':
case '{':
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;
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 < 11; 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 for main1
}// Of CharStack
运行结果
The current stack is:
Is the expression [2 + (1 - 3)] * 4bracket matching?true
Is the expression ( ) )bracket matching?false
Is the expression ()()(())bracket matching?true
Is the expression ({}[])bracket matching?false
Is the expression )(bracket matching?false
Q&A
Q1: bracketMatching是什么?
A1:所谓括号匹配,可以延伸出许多匹配问题,不限于括号。只要是两个字符就可以设置成匹配关系。常见的匹配关系:(), [], {}, ##, “”, ‘’, &&。这里就三种括号((),[],{})的匹配来进行编写。