[LeetCode]#942. DI String Match

  • If S[i] == "I", then A[i] < A[i+1]
  • If S[i] == "D", then A[i] > A[i+1]
Input: "IDID"
Output: [0,4,1,3,2]
  1. Set low=0 and high is 4 based on S.
  2. If S[i] is “I”, add low to ans list and low add 1.
  3. If S[i] is “D”, add high to ans list and high decrease 1.
  4. The last list you can add low and high are OK.
class Solution:
def diStringMatch(self, S):
low,high=0,len(S)
ans=[]
for i in S:
if i=="I":
ans.append(low)
low+=1
else:
ans.append(high)
high-=1
return ans +[low]

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store