1.括号匹配
检查一个字符串的括号是否匹配. 所谓匹配, 是指每个左括号有相应的一个右括号与之对应, 且左括号不可以出现在右括号右边. 可以修改测试字符串, 检查不同情况下的运行.
实现要求:
1、左括号必须用相同类型的右括号闭合。
2、左括号必须以正确的顺序闭合。
2.代码实现:
步骤:
- 创建一个新的栈,将#入新栈
- 遍历判断栈,每读一个左括号,就入新栈
- 读到一个右括号,先在新栈出栈一个元素,并配备与该右括号是否匹配,若不匹配,则直接返回false,若匹配,就继续运行
- 最后判断新栈的最后一个元素是否是#,若不是,则匹配失败
package com.datastructure;
public class CharStack {
public static final int MAX_DEPTH = 10;
int depth;
char[] data;
public CharStack() {
depth = 0;
data = new char[MAX_DEPTH];
}// of the first constructor
public String toString() {
String resultString = "";
for (int i = 0; i < depth; i++) {
resultString += data[i] + " ";
} // of for i
return resultString;
}// of toString
//入栈
public boolean push(char paraChar) {
if (depth == MAX_DEPTH) {
System.out.println("Stack full.");
return false;
}
data[depth] = paraChar;
depth++;
return true;
}// of push
//出栈
public char pop() {
if (depth == 0) {
System.out.println("Nothing to pop.");
return '\0';
}
char resultChar = data[depth - 1];
depth--;
return resultChar;
}// of pop
public static boolean bracketMatching(String paraString) {
//创建一个新的栈,将#入新栈
CharStack tempStack = new CharStack();
tempStack.push('#');
char tempChar, tempPopedChar;
//遍历判断栈
for (int i = 0; i < paraString.length(); i++) {
tempChar = paraString.charAt(i);
//每读一个左括号,就入新栈
switch (tempChar) {
case '(':
case '[':
case '{':
tempStack.push(tempChar);
break;
//读到一个右括号,先在新栈出栈一个元素,并配备与该右括号是否匹配,若不匹配,则直接返回false
case ')':
tempPopedChar = tempStack.pop();
if (tempPopedChar != '(') {
return false;
}
break;
case ']':
tempPopedChar = tempStack.pop();
if (tempPopedChar != '[') {
return false;
}
break;
case '}':
tempPopedChar = tempStack.pop();
if (tempPopedChar != '{') {
return false;
}
break;
}// of switch
} // of for
//判断新栈的最后一个元素是否是#
tempPopedChar = tempStack.pop();
if (tempPopedChar != '#') {
return false;
} // of if
return true;
}// of bracketMatching
public static void main(String args[]) {
CharStack tempStack = new CharStack();
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
}// of class
测试结果: