6.蓝桥杯之括号问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sword_anyone/article/details/89182685

下面的代码用于判断一个串中的括号是否匹配所谓匹配是指不同类型的括号必须左右呼应,可以相互包含,但不能交叉
例如:
…(…[…]…)… 是允许的
…(…[…)…]… 是禁止的
对于 main 方法中的测试用例,应该输出:
false
true
false
false
请分析代码逻辑,并推测划线处的代码。
答案写在“解答.txt”文件中
注意:只写划线处应该填的内容,划线前后的内容不要抄写。


package exe6_10;

import java.util.LinkedList;
import java.util.Scanner;

public class Exe6 {

	static LinkedList  list = new LinkedList();

	public static void main(String args[])
	{
		Scanner scanner = new Scanner(System.in);
		String  string = scanner.next();
		String  strspl[] = string.split("[^\\[\\]\\(\\)]");
		for (int i = 0; i < strspl.length; i++) {
			System.out.print(strspl[i]);
		}

		boolean flag=false;
		try {
			flag = matching(strspl);

		} catch (Exception e) {
			System.out.println("不匹配");
		}
		System.out.println(flag);
	}
    //如果是左【大中小】括号,则把它相对应的右边元素入栈;如果遇到了右边的括号,则弹栈,看是否匹配。此处可用stack
	private static boolean matching(String  strspl[])throws Exception {
		for (int i = 0; i < strspl.length; i++) {
			if (strspl[i].equals("(")) {
				list.add(")");
			}
			else if (strspl[i].equals("[")) {
				list.add("]");
			}
			else if (strspl[i].equals(")")) {
				String str=list.pollLast().toString();
				if (!str.equals(")")) {
					System.out.println("不匹配");
					return false;
				}
			}
			else if (strspl[i].equals("]")) {
				String str=list.pollLast().toString();
				if (!str.equals("]")) {
					System.out.println("不匹配");
					return false;
				}
			}
		}
		return true;
	}

}

支付宝扫红包,让我能够买杯咖啡,继续创作,谢谢大家!
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/sword_anyone/article/details/89182685