数据结构之栈的应用:括号匹配问题

上课的代码我修改了下,类名也不是Client了,注意下,另外将字符串修改为从键盘输入,而且加了个辅助函数判定匹配问题。当然需要用到顺序栈,栈的接口代码,该部分代码参见百度云课程资源http://yun.baidu.com/share/link?shareid=3770451811&uk=1583175585
package mystudy.datastruct;

import java.util.Scanner;

public class BraceMatch {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入一段包含各种左右括号的字符串用以判断是否括号匹配");
		String str = sc.nextLine();
		BraceMatch bm = new BraceMatch();
		if (bm.validateMatch(str))
			System.out.println(str + "中的各种括号是匹配的");
		else
			System.out.println(str + "中的各种括号是不匹配的");
	}

	private boolean validateMatch(String str) {
		IStack stack = new SeqStack();
		char currentChar;// 当前字符
		char popupChar;// 出栈字符
		int len = str.length();
		for (int i = 0; i < len; i++) {
			currentChar = str.charAt(i);
			if (currentChar == '(' || currentChar == '[' || currentChar == '{') {
				stack.push(currentChar);//字符入栈
			} else if (currentChar == ')' || currentChar == ']'
					|| currentChar == '}') {
				if (stack.isEmpty()) { // 比如输入的字符串为"(1-3)*{(5+4)/4}]"
					System.out.println("左括号少于右括号");
					return false;
				} else {
					popupChar = (char) stack.pop();
					//比如出栈元素为‘[’,当前元素为'}',那就不匹配,这里借助一个辅助函数做判定
					if (!isMatch(popupChar, currentChar)) {// 比如输入的字符串为"{(1-3)*[(5+4)/4}]"
						System.out.println("左括号的类型和右括号的类型不匹配");
						return false;
					}
				}
				// 其他字符,不做任何处理
			}
		}

		if (!stack.isEmpty()) {// 比如输入的字符串为"[(1-3)*{(5+4)/4}"
			System.out.println("左括号多于右括号");
			return false;
		} else {
			return true;
		}
	}

	private boolean isMatch(char c1, char c2) {
		if (c1 == '(' && c2 == ')')
			return true;
		else if (c1 == '[' && c2 == ']')
			return true;
		else if (c1 == '{' && c2 == '}')
			return true;
		else
			return false;
	}
}

你可能感兴趣的:(教学日志)