Skip to content

Commit 5d4f9c5

Browse files
committed
Create 1963-minimum-number-of-swaps-to-make-the-string-balanced.kt
1 parent aca4191 commit 5d4f9c5

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// Same as below, using pointer, but more compact solution, time O(N), space O(1)
2+
class Solution {
3+
fun minSwaps(s: String): Int {
4+
var closed = 0
5+
for(c in s){
6+
if(c == '[') closed++
7+
else if (closed > 0) closed--
8+
}
9+
return (closed + 1) / 2
10+
}
11+
}
12+
13+
// Solution using pointer (since we only have 2 chars to check), time O(N), space O(1)
14+
class Solution {
15+
fun minSwaps(s: String): Int {
16+
var mismatches = 0
17+
var closed = 0
18+
for(c in s){
19+
if(c == ']')
20+
if(closed>0)
21+
closed--
22+
else
23+
mismatches++
24+
else{
25+
closed++
26+
}
27+
}
28+
return (mismatches + 1) / 2
29+
}
30+
}
31+
32+
// Stack solution, time O(N), space O(N)
33+
class Solution {
34+
fun minSwaps(s: String): Int {
35+
val stack = Stack<Char>()
36+
var mismatches = 0
37+
for(c in s){
38+
if(c == ']')
39+
if(!stack.isEmpty())
40+
stack.pop()
41+
else
42+
mismatches++
43+
else{
44+
stack.push(c)
45+
}
46+
}
47+
return (mismatches + 1) / 2
48+
}
49+
}

0 commit comments

Comments
 (0)