forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshuffle-string.py
39 lines (34 loc) · 898 Bytes
/
shuffle-string.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
# Time: O(n)
# Space: O(1)
# in-place solution
class Solution(object):
def restoreString(self, s, indices):
"""
:type s: str
:type indices: List[int]
:rtype: str
"""
result = list(s)
for i, c in enumerate(result):
if indices[i] == i:
continue
move, j = c, indices[i]
while j != i:
result[j], move = move, result[j]
indices[j], j = j, indices[j]
result[i] = move
return "".join(result)
# Time: O(n)
# Space: O(1)
import itertools
class Solution2(object):
def restoreString(self, s, indices):
"""
:type s: str
:type indices: List[int]
:rtype: str
"""
result = ['']*len(s)
for i, c in itertools.izip(indices, s):
result[i] = c
return "".join(result)