The function should return a string with balanced parenthesis. The code I wrote is working for all the inputs below. I am using stack data structure. I suppose this should work for all the edge cases. Can this solution be optimized further?
import java.util.ArrayList;
import java.util.Stack;
public class BalanceParenthesis {
public static String balanceParenthesis(String input) {
Stack<String> st = new Stack<>();
ArrayList<Integer> indicesList = new ArrayList<Integer>();
for (int i = 0; i < input.length(); i++) {
if (st.isEmpty()) {
if (input.charAt(i) == ')')
indicesList.add(i);
if (input.charAt(i) == '(')
st.push("(" + i);
} else {
if ((input.charAt(i) == ')') && st.peek().charAt(0) == '(')
st.pop();
if (input.charAt(i) == '(')
st.push("(" + i);
}
}
while (!st.isEmpty())
indicesList.add(Integer.parseInt(String.valueOf(st.pop().charAt(1))));
StringBuffer buff = new StringBuffer();
for (int i = 0; i < input.length(); i++) {
if (!indicesList.contains(i))
buff.append(input.charAt(i));
}
return buff.toString();
}
public static void main(String[] args) {
System.out.println(balanceParenthesis("q(y)s)")); // q(y)s
System.out.println(balanceParenthesis("(((((")); //""
System.out.println(balanceParenthesis(")))")); // ""
System.out.println(balanceParenthesis("(()()(")); //()()
System.out.println(balanceParenthesis(")())(()()(")); // ()()()
System.out.println(balanceParenthesis("((())))")); //((()))
}
}