2014 华为校园招聘机试题——-编程:
题目:给定一组括号如“[ { ( [ ] ) ( ) } ]” ,括号匹配正确,如“[ { ] }”,括号匹配错误,任意给定一组括号,得出其是否匹配。
import java.util.Scanner;
import java.util.Stack;
public class Bracket {
boolean isMatched(String brackets) {
int string_size = brackets.length();
Stack<Character> match = new Stack<Character>();
char symbol;
boolean is_match = true;
for (int i = 0; i < string_size; i++) {
symbol = brackets.charAt(i);
if (symbol == '{' || symbol == '[' || symbol == '(')
match.push(symbol);
if (symbol == '}' || symbol == ']' || symbol == ')') {
if (match.isEmpty()) {
is_match = false;
break;
} else {
if ((symbol == '}' && match.peek() == '{')
|| (symbol == ']' && match.peek() == '[')
|| (symbol == ')' && match.peek() == '('))
match.pop();
else {
is_match = false;
break;
}
}
}
}
if (!match.empty())
is_match = false;
return is_match;
}
public static void main(String[] args) {
Bracket B = new Bracket();
Scanner input = new Scanner(System.in);
String test_string = input.nextLine();
if (B.isMatched(test_string))
System.out.println("Successful match");
else
System.out.println("Failed match");
}
}