华为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);
}
}