Minimum Number of Moves to Make Palindrome LeetCode solution in Python

1
class Solution(object):
2
def minMovesToMakePalindrome(self, s):
3
"""
4
:type s: str
5
:rtype: int
6
"""
7
count, length_of_s = 0, len(s)
8
if length_of_s <= 2:
9
return count
10
for i in reversed(range(length_of_s)):
11
if s[i] != s[0]:
12
continue
13
if i == 0:
14
# move to middle is a speical case which takes len(s)/2 moves then do recursive for remaining part
15
count += len(s) / 2 + self.minMovesToMakePalindrome(s[1:])
16
else:
17
# this move takes len(s)-1 - i (move from i to last index len(s)-1)and then do recursive for remaining part
18
count += (
19
len(s) - 1 - i + self.minMovesToMakePalindrome(s[1:i] + s[i + 1 :])
20
)
21
break
22
return count

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0