The description of the problem
D means a decrease I mean increase
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.
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/di-string-match
an example
Input: s = "IDID"
Output: [0,4,1,3,2]
The intuition for this problem
greedy algorithm for example, we JUST focus on the first element in your return value. There are two cases you will face. First, you will face D means that the second number will be less than your current number. To make the second number flexible, we could just add the biggest number in the position. Second, you maybe see the I means that the second number will be more than your current number., To make the second number flexible, we could just add the smallest number in this position.
The codes for this
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> diStringMatch(string s) {
vector<int> res;
int n = s.size();
int i = 0, j = n;
for (int k = 0; k < n + 1; k++) {
if (s[k] == 'I') {
res.push_back(i++);
} else {
res.push_back(j--);
}
}
return res;
}
};
int main()
{
Solution s;
string s1 = "IDID";
vector<int> res = s.diStringMatch(s1);
for (int i = 0; i < res.size(); i++) {
cout << res[i] << " ";
}
cout << endl;
}
The corresponding results
0 4 1 3 2
|