Shuffle String
The given problem asks to shuffle the characters in a given string s
according to the given indices
. We will follow the mapping given in the indices
array to rearrange the characters in the original string.
Approach
- Create a new list
result
of the same length ass
, initialized with empty strings. - Iterate through
s
andindices
together, placing each character froms
at the index specified inindices
in theresult
list. - Join the
result
list to get the shuffled string.
Code
|
|
Example
For s = "codeleet"
and indices = [4,5,6,7,0,2,1,3]
, the function would return "leetcode"
.
Complexity
The time complexity of this solution is O(n), where n is the length of the given string s
, as we iterate through the string once. The space complexity is also O(n) for the result
list.