Tuesday, 5 September 2017

java - Remove brackets from an algebraic string containing + and – operators

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public class _Math2 {
    /**
    * Remove brackets from an algebraic string containing + and – operators
    * 
    * http://www.geeksforgeeks.org/remove-brackets-algebraic-string-containing-operators/
    * 
    * @param str
    */
   public static String remove_brackets_from_algebric_equation(String str) {
       char[] chars = str.replaceAll("\\s+", "").toCharArray();
       for (int i = 0; i < chars.length; i++) {
           if(chars[i] == '(') {
               findBracket(i,chars);
               break;
           }
       }
       return new String(chars).replaceAll("\\s+", "");
   }
   private static void findBracket(int open, char[] chars) {
       for (int i = open + 1; i < chars.length; i++) {
           if(chars[i] == '(')
               findBracket(i, chars);
           else if(chars[i] == ')') {
               removeBrackets(chars, open, i);
               
               for (int j = 0; j < chars.length; j++) {
                   if(chars[j] == '(') {
                       findBracket(j , chars);
                       break;
                   }
               }
           }
       }
   }

   private static void removeBrackets(char[] chars, int open, int close) {
       char operator = '+';
       for (int i = open - 1; i >= 0; i--) {
           if(chars[i] == '+' || chars[i] == '-') {
               operator = chars[i];
               break;
           }
       }

       chars[open] = ' ';
       chars[close] = ' ';

       if(operator == '+')
           return;

       for (int i = open+1; i < chars.length; i++) {
           char c = chars[i];
           chars[i] = c == '+' ? '-' : c == '-' ? '+' : c;
       }
   }
   

}

No comments:

Post a Comment