日撸 Java 三百行: DAY15 括号匹配

0.主题

今天实现栈的应用——括号匹配。

1.括号匹配

括号匹配要求:

  1. 左括号必须用相同类型的右括号闭合。
  2. 括号闭合的顺序要正确。

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.体会

通过设置非法字符,可以将不同的情况统一成一种写法,可以使程序更简洁。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值