版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zjucor/article/details/84197942
Given a string S
that only contains "I" (increase) or "D" (decrease), let N = S.length
.
Return any permutation A
of [0, 1, ..., N]
such that for all i = 0, ..., N-1
:
- If
S[i] == "I"
, thenA[i] < A[i+1]
- If
S[i] == "D"
, thenA[i] > A[i+1]
Example 1:
Input: "IDID" Output: [0,4,1,3,2]
Example 2:
Input: "III" Output: [0,1,2,3]
Example 3:
Input: "DDI" Output: [3,2,0,1]
Note:
1 <= S.length <= 10000
S
only contains characters"I"
or"D"
.
思路:遇到D就拿前面的,遇到I就拿后面的;先要判断有多少连续的D或者I
class Solution:
def diStringMatch(self, S):
"""
:type S: str
:rtype: List[int]
"""
# from collections import deque
# q=deque([i for i in range(len(S)+1)])
a=[i for i in range(len(S)+1)]
p,q=0,len(a)-1
res=[]
if S[0]=='I':
res.append(a[p])
p+=1
else:
res.append(a[q])
q-=1
i=0
while i<len(S):
j=i
while j<len(S) and S[j]==S[i]: j+=1
if S[i]=='I':
for k in range(j-i):
res.append(q-(j-i-1)+k)
q-=(j-i)
else:
for k in range(j-i):
res.append(p+(j-i-1-k))
p+=(j-i)
i=j
return res