942. DI String Match
阿新 • • 發佈:2018-11-19
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"
A[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