1249. Minimum Remove to Make Valid Parentheses
Previous1239. Maximum Length of a Concatenated String with Unique CharactersNext1275. Find Winner on a Tic Tac Toe Game
Last updated
Last updated
/**
* Time complexity : O(N)
* Space complexity : O(N)
*/
class Solution {
public String minRemoveToMakeValid(String s) {
if(s == null || s.length() == 0) {
return s;
}
int openCount = 0, closeCount = 0;
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) == ')') {
closeCount++;
}
}
StringBuilder sb = new StringBuilder();
for(char ch: s.toCharArray()) {
if(ch == '(') {
if(openCount == closeCount) {
continue;
}
openCount++;
} else if(ch == ')') {
closeCount--;
if(openCount == 0) {
continue;
}
openCount--;
}
sb.append(ch);
}
return sb.toString();
}
}