您的位置:首页 > 编程语言 > Java开发

JAVA蓝桥杯(6)括号问题

2016-01-08 20:49 369 查看

问题描述

下面的代码用于判断一个串中的括号是否匹配所谓匹配是指不同类型的括号必须左右呼应,可以相互包含,但不能交叉

例如:

..(..[..]..)..  是允许的

..(...[...)....].... 是禁止的

对于 main 方法中的测试用例,应该输出:

false

true

false

false

解决方法

import java.util.Stack;

public class Question5 {

public static void main(String[] args) {
System.out.println(isGoodBracket("...(..[.)..].{.(..).}..."));
System.out.println(isGoodBracket("...(...)..."));
System.out.println(isGoodBracket(".....[...].(.).){.(..).}..."));
System.out.println(isGoodBracket("...(..[...].(.).){.(..)...."));
}

private static boolean isGoodBracket(String string) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < string.length(); i++) {
switch (string.charAt(i)) {
case '{':
stack.push('{');
break;
case '[':
stack.push('[');
break;
case '(':
stack.push('(');
break;
case '}':
if (stack.isEmpty()||stack.pop() != '{') {
return false;
}
break;
case ']':
if (stack.isEmpty()||stack.pop() != '[') {
return false;
}
break;
case ')':
if (stack.isEmpty()||stack.pop() != '(') {
return false;
}
break;
}
}
return true;
}
}

运行结果

false
true
false
true
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: