-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathShuffleString.cpp
More file actions
36 lines (25 loc) · 760 Bytes
/
ShuffleString.cpp
File metadata and controls
36 lines (25 loc) · 760 Bytes
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
/*
Source: https://leetcode.com/problems/shuffle-string/
Time: O(n), maximum number of possible iterations is 2 * n, so O(2n) ~ O(n)
Space: O(1), in-place
*/
class Solution {
public:
string restoreString(string s, vector<int>& indices) {
int size = indices.size();
for(int i = 0; i < size; ++i) {
while(i != indices[i]) {
int index = indices[i];
// swap characters according to the indexes provided in the given indices array
char temp = s[index];
s[index] = s[i];
s[i] = temp;
// swap indexes given in the indices array of corresponding characters
int temp1 = indices[index];
indices[index] = indices[i];
indices[i] = temp1;
}
}
return s;
}
};