0.主题
今天实现栈的应用——括号匹配。
1.括号匹配
括号匹配要求:
- 左括号必须用相同类型的右括号闭合。
- 括号闭合的顺序要正确。
2.程序
程序实现的逻辑如下:
- 遇到非括号元素,略过
- 遇到左括号,将其入栈
- 遇到右括号,将栈顶元素出栈,若匹配则处理下一个字符,若栈空无法出栈或者出栈的左括号不匹配,则返回false
- 所有括号处理完毕后,栈内应没有括号,若有则返回false,否则返回true
注:可以通过在栈中填充一个非法字符,将栈空和出栈左括号不匹配两种情况统一成一种,使程序更简洁。
1.程序代码如下:
/**
********************
* 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 (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
时间复杂度:
O
(
n
)
O(n)
O(n),因为需要遍历输入的字符串
空间复杂度:
O
(
n
)
O(n)
O(n),取决于程序执行过程中栈的深度
2.测试
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
3.程序执行结果如下:
3.体会
通过设置非法字符,可以将不同的情况统一成一种写法,可以使程序更简洁。