DEV Community

Discussion on: Daily Challenge #151 - Reverse Parentheses

Collapse
 
dineshbhagat profile image
DB • Edited

Java

Not so good solution

public static String reverseP(String s) {
        if (s == null || "".equals(s)) {
            return s;
        }
        Stack<String> st = new Stack<>();
        StringBuilder mainSb = new StringBuilder();
        int counter = 0;

        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                // push subsequent characters to stack
                // push opposite brace for ease of character pop and no replacement
                st.push(")");
                counter++;
            } else if (s.charAt(i) == ')') {
                st.push("(");
                // pop subsequent characters to stack till you encounter ")" in stack i.e. "(" w.r.t. main string
                StringBuilder sb1 = new StringBuilder();
                while (!st.isEmpty()) {
                    String pop = st.pop();
                    sb1.append(pop);
                    if (pop.equals(")")) {
                        st.push(sb1.toString());
                        // just till last encounter of opening brace and add that to stack
                        break;
                    }
                }
                counter--;
                // if counter is 0 ==> balanced parenthesis,
                // but stack is still contains elements and need to append to main String
                if (counter == 0 && !st.isEmpty()) {
                    while (!st.isEmpty()) {
                        mainSb.append(st.pop());
                    }
                }
            } else if (!st.isEmpty()) {
                st.push("" + s.charAt(i));
            } else {
                mainSb.append(s.charAt(i));
            }
        }
        return mainSb.toString();
    }