package huawei;
import java.util.Scanner;
import java.util.Stack;
/**
* 输入一串字符串,其中有普通的字符与括号组成(包括‘(’、‘)’、‘[’,']'、‘{’,‘}’),
* 要求验证括号是否匹配,如果匹配则输出0、否则输出1.
Sample input:d{fa(sdf)df[dfds(dfd)]}
Sample outPut:0
* @author USER
*
*/
public class MatchBracket {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String string = in.nextLine();
boolean match = doMatch(string);
if (match == true) {
System.out.println(0);
}else {
System.out.println(1);
}
}
private static boolean doMatch(String string) {
// TODO Auto-generated method stub
Stack<Character> stack = new Stack<Character>();
char[] ch = string.toCharArray();
for (int i = 0; i < ch.length; i++) {
switch (ch[i]) { //注意:switch中只能为字符型和int型
case '{':
case '[':
case '(':
stack.push(ch[i]);
break;
case ')':
if (!stack.isEmpty() && stack.pop().equals('(')) {
break;
}else {
return false;
}
case ']':
if (!stack.isEmpty() && stack.pop().equals('[')) {
break;
}else {
return false;
}
case '}':
if (!stack.isEmpty() && stack.pop().equals('{')) {
break;
}else {
return false;
}
default:
break;
}
}
if (stack.isEmpty()) {
return true;
}else {
return false;
}
}
}
华为机试练习---括号匹配问题
最新推荐文章于 2024-09-25 19:16:13 发布