forked from srishilesh/Data-Structure-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1249_Min_remove_to_make_valid_parenthesis
67 lines (63 loc) · 2 KB
/
1249_Min_remove_to_make_valid_parenthesis
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/
// APPROACH 2
class Solution {
public String minRemoveToMakeValid(String s) {
Stack<Integer> stack = new Stack<Integer>();
String[] arr = s.split("");
for (int i=0; i<arr.length; i++) {
if (arr[i].equals("("))
stack.push(i);
if (arr[i].equals(")")) {
if (!stack.isEmpty())
stack.pop();
else
arr[i] = "";
}
}
while (!stack.isEmpty())
arr[stack.pop()] = "";
return String.join("",arr);
}
}
// APPROACH 1
// class Solution {
// public String minRemoveToMakeValid(String s) {
// StringBuilder sb = new StringBuilder(s);
// Stack<Integer> stack = new Stack<Integer>();
// for (int i=0; i<sb.length(); i++) {
// if (sb.charAt(i) == '(')stack.add(i);
// if (sb.charAt(i) == ')') {
// if (!stack.isEmpty())
// stack.pop();
// else
// sb.setCharAt(i, '*');
// }
// }
// while (!stack.isEmpty())
// sb.setCharAt(stack.pop(),'*');
// return sb.toString().replaceAll("\\*","");
// }
// }
// MY APPROACH - FAILED
// class Solution {
// public String minRemoveToMakeValid(String s) {
// Stack<Character> stack = new Stack<Character>();
// int left = 0;
// String ans = "";
// for (char ch : s.toCharArray()) {
// if (Character.isLetter(ch))
// ans += ch;
// else {
// if (ch == '(') {
// ans += ch;
// stack.push(ch);
// }
// else {
// if (!stack.isEmpty() && stack.pop() == '(')
// ans += ch;
// }
// }
// }
// return ans;
// }
// }