[LeetCode]#942. DI String Match

Fatboy Slim
1 min readMay 10, 2020

--

Environment: Python 3.7

Key technique: append function

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", then A[i] < A[i+1]
  • If S[i] == "D", then A[i] > A[i+1]

Example 1:

Input: "IDID"
Output: [0,4,1,3,2]

Analysis:

  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.

Solution:

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]

Submissions:

Reference:

https://leetcode.com/problems/di-string-match/solution/

--

--

Fatboy Slim
Fatboy Slim

Written by Fatboy Slim

Interesting in any computer science.

No responses yet