0%

1528. Shuffle String

类似快慢指针找cycle O(n) time O(1) space

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
string restoreString(string s, vector<int>& indices) {
for (int i = 0; i < indices.size(); ++i) {
while (i != indices[i]) { // 只要当前位置不是正确的index就一直swap
swap(s[i], s[indices[i]]); // 保持字符串跟indices数组同步即可
swap(indices[i], indices[indices[i]]);
}
}
return s;
}
};