-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
56 lines (53 loc) · 1.31 KB
/
Solution.java
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
class Solution {
public int minAddToMakeValid(String s) {
int balance = 0; // keeps track of how many more opening parentheses we have compared to closing
// ones as we process the string
int moves = 0;// counts how many parentheses we need to add to make the string valid
for (char c : s.toCharArray()) {
if (c == '(') {
balance++;
} else if (c == ')') {
balance--;
}
if (balance < 0) {
moves++;
balance = 0;
}
}
return moves + balance;
}
}
/*
*
* import java.util.Stack;
*
* public class Solution {
* public int minAddToMakeValid(String s) {
* Stack<Character> stack = new Stack<>();
* int moves = 0;
*
* for (char c : s.toCharArray()) {
* if (c == '(') {
* stack.push(c);
* } else if (c == ')') {
* if (!stack.isEmpty()) {
* stack.pop();
* } else {
* moves++;
* }
* }
* }
*
* return moves + stack.size(); // Moves for unmatched closing + remaining
* opening
* }
*
* public static void main(String[] args) {
* Solution sol = new Solution();
*
* // Test examples
* System.out.println(sol.minAddToMakeValid("())")); // Output: 1
* System.out.println(sol.minAddToMakeValid("(((")); // Output: 3
* }
* }
*/