You are given a string s that contains only the characters 'I' (for “increase”) and 'D' (for “decrease”). Let n be the length of the string s. The goal is to construct an array perm of length n + 1 where:
perm contains all integers from 0 to n.i from 0 to n - 1:
s[i] is 'I', then perm[i] < perm[i + 1].s[i] is 'D', then perm[i] > perm[i + 1].You need to return one such array perm.
Input: s = "IDID"
Output: [0, 4, 1, 3, 2]
s is empty, we should return a single-element array [0].s is always valid and contains only ‘I’ and ‘D’.low starting at 0 and high starting at n.s.low to the result array and increment low.high to the result array and decrement high.low (or high, since they would be equal at this point) to the result array.s once, performing O(1) operations in each iteration.#include <vector>
#include <string>
std::vector<int> diStringMatch(const std::string& s) {
int n = s.length();
std::vector<int> perm(n + 1);
int low = 0, high = n;
for (int i = 0; i < n; ++i) {
if (s[i] == 'I') {
perm[i] = low++;
} else {
perm[i] = high--;
}
}
perm[n] = low; // low and high should be the same at this point
return perm;
}
low to 0 and high to n.s.low or high to the perm array and update the pointers.perm.This gives us the required permutation array that satisfies the conditions for ‘I’ and ‘D’.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?