Press "Enter" to skip to content

Posts tagged as “DI”

花花酱 LeetCode 942. DI String Match

Problem

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]

Example 2:

Input: "III"
Output: [0,1,2,3]

Example 3:

Input: "DDI"
Output: [3,2,0,1]

Note:

  1. 1 <= S.length <= 10000
  2. SĀ only contains charactersĀ "I"Ā orĀ "D".

Solution: Greedy

“I” -> use the smallest possible number

“D” -> use the largest possible number

Time complexity: O(n)

Space complexity: O(n)

C++