forked from Revnth/Hacktoberfest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathha.py
62 lines (48 loc) · 955 Bytes
/
ha.py
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
# Python3 Program to count
# swaps required to balance
# string
# Function to calculate
# swaps required
def swapCount(s):
# Keep track of '['
pos = []
for i in range(len(s)):
if(s[i] == '['):
pos.append(i)
# To count number
# of encountered '['
count = 0
# To track position
# of next '[' in pos
p = 0
# To store result
sum = 0
s = list(s)
for i in range(len(s)):
# Increment count and
# move p to next position
if(s[i] == '['):
count += 1
p += 1
elif(s[i] == ']'):
count -= 1
# We have encountered an
# unbalanced part of string
if(count < 0):
# Increment sum by number
# of swaps required
# i.e. position of next
# '[' - current position
sum += pos[p] - i
s[i], s[pos[p]] = (s[pos[p]],
s[i])
p += 1
# Reset count to 1
count = 1
return sum
# Driver code
s = "[]][]["
print(swapCount(s))
s = "[[][]]"
print(swapCount(s))
# This code is contributed by jsdf