-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDI String Match
More file actions
40 lines (37 loc) · 1.07 KB
/
DI String Match
File metadata and controls
40 lines (37 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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:
Input: s = "IDID"
Output: [0,4,1,3,2]
Example 2:
Input: s = "III"
Output: [0,1,2,3]
Example 3:
Input: s = "DDI"
Output: [3,2,0,1]
--------------------------------------------------------------------------------------------------------------------------------------------------
// tc=O(n) sc=O(n)
class Solution {
public:
vector<int> diStringMatch(string s) {
int n=s.size();
vector<int>res;
int i=0, j=n;
int k=0;
while(k<n){
if(s[k]=='I'){
res.push_back(i);
i++;
}
else{
res.push_back(j);
j--;
}
k++;
}
res.push_back(i);
return res;
}
};