首页 > 试题广场 >

给定一个字符串的格式如下:(a,(b,1),(2,(c,a)

[问答题]
给定一个字符串的格式如下:(a,(b,1),(2,(c,a),5)),括号内的元素可以是任意的数字或字母,也可以是一个括号。请实现一个算法用于消除表达式内嵌套的括号,例如将上面的表达式变为(a,b,1,2,c,a,5),如果表达式有误请报错。
public class Main{
    String str_input;
    public static void main(String[] args){
         Main m = new Main();
          m.input();
          m.cal();
    }
   public void input(){
        Scanner sc = new Scanner(System.in); str = sc.nextLine();
        str_input = sc.nextLine();
    }
    public void cal(){
        Stack<Character> stack = new Stack<>();
        String result = "(";
        char[] c = str_input.toCharArray();
        for(int i = 1; i < c.length - 1; i ++){
            if(c[i] == '('){
                stack.push(c[i]);
            }
            else if(c[i] == ')'){
                if(!stack.empty()){
                    stack.pop();
                }
                else{
                    throw new Exception;
                }
            }
            else{
                result += c[i];
            }
        }
        if(!stack.empty)){         throw new Exception; }
        else{
            result += ')';
            System.out.println(result);
        }
    }
}

发表于 2019-06-01 13:19:30 回复(0)
更多回答
这题在于需要判断括号是否成对,但是题目中的此条件很隐晦,以为只是单纯的去括号。
  1.     String removeBrackets(String str) {
            int len = str.length();
            Stack<String> stack = new Stack<String>();
            String reStr = "(";
            for (int i=0; i<len; i++) {
                String strI = str.substring(i, i+1);
                if ("(".equals(strI)) {
                    stack.push(strI);
                } else if (")".equals(strI)) {
                    if (stack.empty()) return "Error";
                    stack.pop();
                } else {
                    reStr = reStr + strI;
                }
            }
            if(!stack.empty()) return "Error";
            return reStr + ")";
        }
编辑于 2019-05-30 15:58:31 回复(1)
YL,头像 YL,
public class Test03 { public static void main(String[] args) {
        Stack<Character> stack = new Stack<Character> ();
        String s = "(a,(b,1),(2,(c,a),5))";
        String resultStr = "("; for (int i = 0;i<s.length();i++){ if (s.charAt(i) == '('){
               stack.push('(');
           }else if (s.charAt(i) == ')'){ if (stack.isEmpty()){
                   System.out.println("Error!"); break;
               } if (stack.peek() == '(') {
                   stack.pop();
               }
           } else{
               resultStr += s.charAt(i);
           }
        } if (stack.size() == 0){
            System.out.println(resultStr+")");
        }else{
            System.out.println("Error");
        }
    }

}

发表于 2019-07-18 19:54:46 回复(1)
public static String RemoveBrackets(String s){
        Stack<Character> stack = new Stack<Character>();
        String resultStr = "(";
        for(int i = 0;i<s.length();i++){
            if(s.charAt(i)=='('){
                stack.push('(');    
            }else if(s.charAt(i)==')'){
                if(stack.empty()){
                    return "Error";
                }else if(stack.peek()!='('){
                    return "Error";
                }else{
                    stack.pop();
                }
            }else{
                resultStr +=s.charAt(i);
            }
        }
        if(!stack.empty()){
            return "Error";
        }
        return resultStr+")";
    }
发表于 2019-09-16 21:02:27 回复(0)
通过示例的字符串来获取相应的坐标然后拼接一下就好了
public static void main(String[] args) {
        System.out.println(getString("(a,(b,1),(2,(c,a),5))"));
}
private static String getString(String input) {
        String s = "(a,(b,1),(2,(c,a),5))";
        int[] index = new int[7];
        int j = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c != '(' && c != ')' && c != ',') {
                if (c < 48 || 57 < c && c < 65 || c > 90 && c < 97 || c > 122)
                    return "error";
                index[j] = i;
                j++;
            }
        }
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("(");
        for (int i = 0; i < j; i++) {
            char c = input.charAt(index[i]);
            stringBuilder.append(c);
            if (i < j - 1) stringBuilder.append(",");
        }
        stringBuilder.append(")");
        return stringBuilder.toString();
    }

发表于 2023-03-07 16:54:58 回复(0)
import java.util.*;

public class test16 {
    public static void main(String[] args) {
        Stack<Character> stack = new Stack<>();
        String s = "(a,(b,1),(2,(c,a),5))";
        String res = "(";
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                stack.push('(');
            } else if (s.charAt(i) == ')') {
                if (stack.isEmpty()) {
                    System.out.println("error");
                    break;
                } else if (stack.peek() == '(') {
                    stack.pop();
                }
            } else {
                res += s.charAt(i);
            }
        }
        if (stack.size() == 0) {
            System.out.println(res + ')');
        } else {
            System.out.println("error");
        }

    }

}

发表于 2022-07-23 09:45:18 回复(0)
public class Main { public static void main(String[] args) {
        Scanner input =new Scanner(System.in);  String s =input.nextLine();  String s2=forEachString(s.split("\\)"));  String s3=forEachString(s2.split("\\("));  System.out.println("("+s3+")");  } public static String forEachString(String[] String1){
        StringBuffer s=new StringBuffer();  for (String ss:String1
             ) {
            s.append(ss);  } return s.substring(0);  }
}
发表于 2020-08-16 19:01:37 回复(0)
public class six {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        Stack<Character> stack = new Stack<Character>();
        for (int i = 0; i < str.length(); i++) {
            stack.add(str.charAt(i));
        }
        str = "";
        boolean is = true;
        int n =stack.size();
        for (int i = 0; i < n; i++) {
            if(i==0&&stack.peek()!=')'){
                is = false;
                break;
            }else if(i == n-1 && stack.peek()!='('){
                is = false;
                break;
            }else{
                if(i == 0){
                    str+=stack.pop();
                }else if(i == n-1){
                    str += stack.pop();
                }else{
                    if(stack.peek()==')'||stack.peek()=='('){
                        stack.pop();
                    }
                    else{
                        str+=stack.pop();
                    }
                }
            }
            
        }
        String str1 = "";
        if(is){
            for (int i = str.length()-1; i >=0 ; i--) {
                str1 += str.charAt(i);
            }
            System.out.println(str1);
        }else{
            System.out.println("输入有误!");
        }
    }
}

发表于 2019-09-17 22:01:53 回复(0)
public class Main {

	public static void main(String[] args) {
		Stack<Character> stack=new Stack<Character>();
		Scanner sc=new Scanner(System.in);
		String s=sc.next();
		
		String res="(";
		for(int i=0;i<s.length();i++){
			if(s.charAt(i)=='('){
				stack.push(s.charAt(i));
			}else if(s.charAt(i)==')'){
				if(stack.isEmpty()){
					System.out.println("Error!");
					break;
				}
				if(stack.peek()=='('){
					stack.pop();
				}
			}else{
				res+=s.charAt(i);
			}
		}
		if(stack.size()==0){
			System.out.println(res+")");
		}else{
			System.out.println("Error!");
		}

	}

}

发表于 2019-08-25 11:06:00 回复(0)
如果是(......)(....)这样的表达式呢
发表于 2019-08-11 00:02:36 回复(0)
String str = "(a,(b,1),(2,(c,a),5))";
str.replaceAll(")","");
str.replaceAll("(","");
发表于 2019-07-22 15:01:21 回复(0)
思路:把数组放入一个Linklisted的队列中,然后遍历,如果是(,或者)则删除

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.management.Query;

public class Test {
    public void delethuohao(String array) {
        Queue queue=new LinkedList();
        int len=array.length();
        char[] chararray=new char[len];
        for(int i=0;i<len;i++) {
            chararray[i]=array.charAt(i);
        }
        
        for(int i=0;i<len;i++) {
            if(i==0||i==len-1) {
                queue.add(chararray[i]);
            }
            if(chararray[i]!='('&&chararray[i]!=')') {
                queue.add(chararray[i]);
            }
        
        }
            
            System.out.print(queue.toString());
        
        
    }
    public static boolean hefa(String array) {
        String regex="/w+,+)+(";
        Pattern pattern=Pattern.compile(regex);
        Matcher matcher=pattern.matcher(array);
        return matcher.matches();
    }
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        String array=scanner.nextLine();
        Test test=new Test();
        //如何判断是数字和字母还有括号符合这个要求
        //if(hefa(array)) {
            test.delethuohao(array);
            
        //}else {
        //    new RuntimeException("输入不合法");
    //    }
        
    }

}


发表于 2019-07-20 09:45:19 回复(0)
public class Test2 {          private static String input_string;     public static void main(String[] args) {         System.out.println("input a string:");         Scanner sc = new Scanner(System.in);         input_string = sc.nextLine();         String result = cal(input_string);         System.out.println("after:"+result);         sc.close();     }          private static String cal(String str) {         StringBuilder result = new StringBuilder("(");         char[] arr = str.toCharArray();         ArrayList<Character> list = new ArrayList<Character>(arr.length);         for(int i=0;i<arr.length;i++) {             if(arr[i] != '(' && arr[i] != ')') {                 list.add(arr[i]);             }         }         for(int i=0;i<list.size();i++) {             result.append(list.get(i));         }         result.append(")");         return result.toString();     }

}

发表于 2019-06-10 10:38:32 回复(0)
public class Test2 {          private static String input_string;     public static void main(String[] args) {         System.out.println("input a string:");         Scanner sc = new Scanner(System.in);         input_string = sc.nextLine();         String result = cal(input_string);         System.out.println("after:"+result);         sc.close();     }          private static String cal(String str) {         StringBuilder result = new StringBuilder("(");         char[] arr = str.toCharArray();         ArrayList<Character> list = new ArrayList<Character>(arr.length);         for(int i=0;i<arr.length;i++) {             if(arr[i] != '(' && arr[i] != ')') {                 list.add(arr[i]);             }         }         for(int i=0;i<list.size();i++) {             result.append(list.get(i));         }         result.append(")");         return result.toString();     }

}

发表于 2019-06-10 09:38:03 回复(0)