Leetcode 1528. Shuffle String Sure, let’s break down the problem:
You are given a string s
and an integer array indices
of the same length. The string s
will be rearranged such that the character at the i
th position moves to indices[i]
in the shuffled string. Return the shuffled string.
Input: s = "code", indices = [3, 1, 2, 0]
Output: "edoc"
Explanation: As the indices are [3, 1, 2, 0], the characters of s will be moved to the respective positions: "c" -> 3, "o" -> 1, "d" -> 2, "e" -> 0. Thus, the output is "edoc".
s
unique?
s
?
100
.Let’s proceed to the strategy and code.
result
of the same length as s
and initialize it with empty spaces or any placeholder character.indices
array.Here’s the C++ code implementation:
#include <iostream>
#include <vector>
#include <string>
std::string restoreString(const std::string& s, const std::vector<int>& indices) {
int n = s.size();
std::string result(n, ' '); // Initialize a result string with spaces of the same length as s
for (int i = 0; i < n; ++i) {
result[indices[i]] = s[i]; // Place each character at the correct position
}
return result; // Return the rearranged result
}
int main() {
std::string s = "code";
std::vector<int> indices = {3, 1, 2, 0};
std::string shuffled = restoreString(s, indices);
std::cout << "Shuffled string: " << shuffled << std::endl;
return 0;
}
The time complexity of this solution is:
n
is the length of the string s
. This is because we are iterating through the string once and placing each character in its appropriate position.The space complexity is also:
n
is the length of the string s
. This is due to the creation of the result string which requires additional space equal to the input string.Feel free to ask any further clarifying questions or for additional help!
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?