class Solution {
/**
* A valid pair is considered, when I have seen a left paren first and then I saw a right paren.
* 1) find the total count (n) of properly paired parenthesis, so there are n number of '(' and n number of ')'
* 2) iterate over the string, if you see an '(', add it and decrement counter
* If you see an ')', add it as well and decrement the counter
* once the counter reaches 0, do not add any of the respective
**/
public String minRemoveToMakeValid(String s) {
if (s == null || s.length() == 0)
return s;
int pairCount = getValidParenPairCount(s) ;
return getStringWithValidParen(s, pairCount);
}
private String getStringWithValidParen(String s, int pairCount) {
int leftCount = pairCount;
int rightCount = pairCount;
StringBuilder sb = new StringBuilder();
int i = 0;
while(i < s.length()) {
char c = s.charAt(i);
switch(c) {
case '(':
if (leftCount > 0) {
sb.append(c);
leftCount--;
}
break;
case ')':
// I have to use a left paren first and then I can take a right paren
if (rightCount > 0 && rightCount > leftCount) {
sb.append(c);
rightCount--;
}
break;
default:
sb.append(c);
break;
}
i++;
}
return sb.toString();
}
private int getValidParenPairCount(String s) {
Stack<Character> st = new Stack<Character>();
int count = 0;
int i = 0;
while(i < s.length()) {
char c = s.charAt(i);
switch(c) {
case '(':
st.push(c);
break;
case ')':
if (!st.isEmpty()) {
st.pop();
count++;
}
break;
default:
break;
}
i++;
}
return count;
}
}