File tree Expand file tree Collapse file tree 1 file changed +69
-0
lines changed Expand file tree Collapse file tree 1 file changed +69
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Time: O(nlogn)
2
+ # Space: O(n)
3
+
4
+ class BIT (object ): # 0-indexed
5
+ def __init__ (self , n ):
6
+ self .__bit = [0 ]* (n + 1 )
7
+
8
+ def add (self , i , val ):
9
+ i += 1
10
+ while i < len (self .__bit ):
11
+ self .__bit [i ] += val
12
+ i += (i & - i )
13
+
14
+ def query (self , i ):
15
+ i += 1
16
+ ret = 0
17
+ while i > 0 :
18
+ ret += self .__bit [i ]
19
+ i -= (i & - i )
20
+ return ret
21
+
22
+
23
+ # greedy, bit, fenwick tree
24
+ class Solution (object ):
25
+ def minMovesToMakePalindrome (self , s ):
26
+ """
27
+ :type s: str
28
+ :rtype: int
29
+ """
30
+ idxs = [[] for _ in xrange (26 )]
31
+ for i , c in enumerate (s ):
32
+ idxs [ord (c )- ord ('a' )].append (i )
33
+ targets , pairs = [0 ]* len (s ), []
34
+ for c , idx in enumerate (idxs ):
35
+ for i in xrange (len (idx )// 2 ):
36
+ pairs .append ((idx [i ], idx [~ i ]))
37
+ if len (idx )% 2 :
38
+ targets [idx [len (idx )// 2 ]] = len (s )// 2
39
+ pairs .sort ()
40
+ for i , (l , r ) in enumerate (pairs ):
41
+ targets [l ], targets [r ] = i , (len (s )- 1 )- i
42
+ bit = BIT (len (s ))
43
+ result = 0
44
+ for i in targets :
45
+ result += i - bit .query (i - 1 ) # move from bit.query(i-1) to i
46
+ bit .add (i , 1 )
47
+ return result
48
+
49
+
50
+ # Time: O(n^2)
51
+ # Space: O(n)
52
+ # greedy
53
+ class Solution2 (object ):
54
+ def minMovesToMakePalindrome (self , s ):
55
+ """
56
+ :type s: str
57
+ :rtype: int
58
+ """
59
+ s = list (s )
60
+ result = 0
61
+ while s :
62
+ i = s .index (s [- 1 ])
63
+ if i == len (s )- 1 :
64
+ result += i // 2
65
+ else :
66
+ result += i
67
+ s .pop (i )
68
+ s .pop ()
69
+ return result
You can’t perform that action at this time.
0 commit comments