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 i
-th position moves to indices[i]
in the shuffled string. Return the shuffled string.
Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
Output: "leetcode"
s
and indices
are always the same?
indices
always unique and within the range [0, len(s)-1]?
shuffled
of the same length as s
.indices
array:
i
, place the character s[i]
at the position indices[i]
in the shuffled
list.shuffled
list into a string and return it.s
. This is because we are iterating through the list once and performing constant-time operations for each character.def restoreString(s, indices):
# Initialize a list of the same length as s with empty strings
shuffled = [''] * len(s)
# Place each character at its new index
for i in range(len(s)):
shuffled[indices[i]] = s[i]
# Join the list into a string and return
return ''.join(shuffled)
# Example usage
s = "codeleet"
indices = [4, 5, 6, 7, 0, 2, 1, 3]
print(restoreString(s, indices)) # Output: "leetcode"
This code creates a new list shuffled
which stores the characters of s
rearranged according to the indices
list, and then returns the joined string.
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?