-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathleetcode_min_swaps_palindrome.py
69 lines (53 loc) · 1.41 KB
/
leetcode_min_swaps_palindrome.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
63
64
65
66
67
68
69
from collections import Counter
import sys
''' minimum swaps to make string palindrome'''
# Function to Count minimum swap
def CountSwap(s, n):
s = list(s)
# Counter to count minimum swap
count = 0
ans = True
# A loop which run in half string
# from starting
for i in range(n // 2):
# Left pointer
left = i
# Right pointer
right = n - left - 1
# A loop which run from right pointer
# to left pointer
while left < right:
# if both char same then
# break the loop if not
# same then we have to move
# right pointer to one step left
if s[left] == s[right]:
break
else:
right -= 1
# it denotes both pointer at
# same position and we don't
# have sufficient char to make
# palindrome string
if left == right:
ans = False
break
else:
for j in range(right, n - left - 1):
(s[j], s[j + 1]) = (s[j + 1], s[j])
count += 1
if ans:
return (count)
else:
return -1
def main():
# Driver Code
s = sys.stdin.readline().strip()
# Legth of string
n = len(s)
# Function calling
ans1 = CountSwap(s, n)
ans2 = CountSwap(s[::-1], n)
print(max(ans1, ans2))
if __name__ == "__main__":
main()