简要描述:
- 一个函数消除字符串中成对的括号,括号必须成对匹配,否则打印 “ERROR”;
示例:
给定字符串"(1(23456(789)a)bc)",打印结果"123456789abc";
给定字符串"1(23456(789)abc))",打印结果"ERROR";
返回示例
public static void main(String[] args) {
String a1 = "(1(23456(789)a)bc)";
String a2 = "1(23456(789)abc))";
removeBrackets(a1);
removeBrackets(a2);
}
private static void removeBrackets(String str){
String temp ="";
String s="";
for(int i=0; i<str.length(); i++){
String a = str.charAt(i) + "";
if (!"(".equals(a) && !")".equals(a)){
s += a;
}
if ("(".equals(a)){
temp += a;
}
if (")".equals(a)){
if (temp.length() == 0){
temp += a;
System.out.println("ERROR");
break;
}
String b = temp.charAt(temp.length()-1)+"";
if ("(".equals(b)){
temp = temp.substring(0,temp.length()-1);
}else{
System.out.println("ERROR");
break;
}
}
}
if (temp.length()==0){
System.out.println(s);
}
}
}
执行结果
123456789abc
ERROR