forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1963-minimum-number-of-swaps-to-make-the-string-balanced.kt
More file actions
49 lines (47 loc) · 1.18 KB
/
1963-minimum-number-of-swaps-to-make-the-string-balanced.kt
File metadata and controls
49 lines (47 loc) · 1.18 KB
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
// Same as below, using pointer, but more compact solution, time O(N), space O(1)
class Solution {
fun minSwaps(s: String): Int {
var closed = 0
for(c in s){
if(c == '[') closed++
else if (closed > 0) closed--
}
return (closed + 1) / 2
}
}
// Solution using pointer (since we only have 2 chars to check), time O(N), space O(1)
class Solution {
fun minSwaps(s: String): Int {
var mismatches = 0
var closed = 0
for(c in s){
if(c == ']')
if(closed>0)
closed--
else
mismatches++
else{
closed++
}
}
return (mismatches + 1) / 2
}
}
// Stack solution, time O(N), space O(N)
class Solution {
fun minSwaps(s: String): Int {
val stack = Stack<Char>()
var mismatches = 0
for(c in s){
if(c == ']')
if(!stack.isEmpty())
stack.pop()
else
mismatches++
else{
stack.push(c)
}
}
return (mismatches + 1) / 2
}
}