DI String Match Problem


Description

LeetCode Problem 942.

A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where:

  • s[i] == ‘I’ if perm[i] < perm[i + 1], and
  • s[i] == ‘D’ if perm[i] > perm[i + 1].

Given a string s, reconstruct the permutation perm and return it. If there are multiple valid permutations perm, return any of them.

Example 1:

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

Example 2:

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

Example 3:

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

Constraints:

  • 1 <= s.length <= 10^5
  • s[i] is either ‘I’ or ‘D’.


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
    vector<int> diStringMatch(string S) {
        int n = S.size();
        vector<int> ans(n+1, 0);
        
        int p = 0, q = n;
        for (int i = 0; i < n; i ++) {
            if (S[i] == 'I') {
                ans[i] = p;
                p ++;
            } else {
                ans[i] = q;
                q --;
            }
        }
        ans[n] = p;
        
        return ans;
    }
};




Related Posts

Squares Of A Sorted Array Problem

LeetCode 977. Given an integer array nums sorted in non-decreasing...

Sort Array By Parity Problem

LeetCode 905. Given an integer array nums, move all the...

Sort Array By Parity II Problem

LeetCode 922. Given an array of integers nums, half of...

Shortest Distance To A Character Problem

LeetCode 821. Given a string s and a character c...

Reverse Only Letters Problem

LeetCode 917. Given a string s, reverse the string according...

Push Dominoes Problem

LeetCode 838. There are n dominoes in a line, and...