You are given a string s
and an integer array indices
of the same length. The string s
will be shuffled such that the character at the ith
position moves to indices[i]
in the shuffled string.
Return the shuffled string.
s.length == indices.length == n
1 <= n <= 100
s
consists of only lowercase English letters.0 <= indices[i] < n
indices
are unique.Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
Explanation: As shown, “codeleet” becomes “leetcode” after shuffling.
Output: "leetcode"
We can easily solve “Shuffle String” coding problem using single loop. Stepwise breakdown of solution is as follows.
Implementation of above solution in C++ is as follows.
class Solution {
public:
string restoreString(string s, vector<int>& indices) {
int n = s.size();
string answer = s;
for(int i=0; i<n; i++) {
answer[indices[i]] = s[i];
}
return answer;
}
};
O(n)
where n = number of characters in string.
O(n)
where n = number of characters in string.
Thanks for reading and have a nice day.