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.
Example 1:
Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
Output: "leetcode"
Example 2:
Input: s = "abc", indices = [0,1,2]
Output: "abc"
s
?
s.length
≤ 100).indices
array unique?
indices
is a permutation of the array 0
to n-1
.shuffled
of the same length as s
.s
and place each character to its correct index as specified in the indices
array.shuffled
back to a string and return it.public class ShuffleString {
public String restoreString(String s, int[] indices) {
// Create a character array to hold the shuffled version
char[] shuffled = new char[s.length()];
// Iterate over the input string and place each character to its new position
for (int i = 0; i < s.length(); i++) {
shuffled[indices[i]] = s.charAt(i);
}
// Convert the character array back to a string
return new String(shuffled);
}
public static void main(String[] args) {
ShuffleString shuffleString = new ShuffleString();
System.out.println(shuffleString.restoreString("codeleet", new int[]{4,5,6,7,0,2,1,3})); // Outputs: "leetcode"
System.out.println(shuffleString.restoreString("abc", new int[]{0,1,2})); // Outputs: "abc"
}
}
O(n)
, where n
is the length of the string s
. We iterate over the string s
once to rearrange the characters.O(n)
, where n
is the length of the string s
. We use an additional array of the same length as s
to store the characters in their shuffled positions.This implementation ensures that the string is shuffled correctly based on the provided indices
array in linear time, making it efficient for typical input sizes.
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?