-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathdi-string-match.py
43 lines (41 loc) · 928 Bytes
/
di-string-match.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
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/84206493
class Solution:
def diStringMatch(self, S):
"""
:type S: str
:rtype: List[int]
"""
N = len(S)
ni, nd = 0, N
res = []
for s in S:
if s == "I":
res.append(ni)
ni += 1
else:
res.append(nd)
nd -= 1
res.append(ni)
return res
# V2
# Time: O(n)
# Space: O(1)
class Solution(object):
def diStringMatch(self, S):
"""
:type S: str
:rtype: List[int]
"""
result = []
left, right = 0, len(S)
for c in S:
if c == 'I':
result.append(left)
left += 1
else:
result.append(right)
right -= 1
result.append(left)
return result