-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathValidString
More file actions
26 lines (25 loc) · 769 Bytes
/
ValidString
File metadata and controls
26 lines (25 loc) · 769 Bytes
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
import java.util.Stack;
public class ValidString {
public String minRemovalToMakeValid(String s) {
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
stack.push(i);
} else if (c == ')') {
if (!stack.isEmpty() && s.charAt(stack.peek()) == '(') {
stack.pop();
} else {
stack.push(i);
}
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (!stack.contains(i)) {
sb.append(s.charAt(i));
}
}
return sb.toString();
}
}