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

华为-成研所笔试-java-括号匹配

2015-04-23 23:02 351 查看
华为2015年暑假实习生成研所笔试(机试)题目 第二题 括号匹配

三种括号 []{}()

括号匹配规则:

{{()[]}} 则为true;

{[()}} 则为false 并打印出未匹配位置;

源码为

import java.util.Scanner;
import java.util.Stack;

public class Test {
public static void main(String[] args) {
Stack<Character> stack = new Stack<Character>();
Scanner sc = new Scanner(System.in);
char[] b = sc.nextLine().toCharArray();
boolean result = false;
int count = 0;
for (char c : b) {
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
} else if (c == ')' || c == ']' || c == '}') {
switch (c) {
case ')': {
if (!stack.isEmpty())
result = stack.pop() == '(' ? true : false;
if (!result)
break;
}
case '}': {
if (!stack.isEmpty())
result = stack.pop() == '{' ? true : false;
if (!result)
break;
}
case ']': {
if (!stack.isEmpty())
result = stack.pop() == '[' ? true : false;
if (!result)
break;
}
default: {
}
}
}
count++;
}
count = result ? 0 : count;
System.out.println("result=" + result + count);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: