LeetCode 1528: Shuffle String Solution
Master LeetCode problem 1528 (Shuffle String), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation
To shuffle the string according to the given indices, we can create a new string and iterate through the characters in the original string s. For each character at index i in s, we place it at the corresponding index indices[i] in the new string.
Algorithm
- Create a character array of size
n, wherenis the length of the input strings. - Iterate through the characters in
sand place each character at the corresponding index in the new array usingindices. - Convert the character array to a string and return the shuffled string.
Time Complexity
The time complexity of this algorithm is O(n), where n is the length of the input string s.
Space Complexity
The space complexity of this algorithm is O(n) as well, where n is the length of the input string s.
Solution Code
class Solution {
public String restoreString(String s, int[] indices) {
char[] shuffled = new char[s.length()];
for (int i = 0; i < s.length(); i++) {
shuffled[indices[i]] = s.charAt(i);
}
return new String(shuffled);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1528 (Shuffle String)?
This page provides optimized solutions for LeetCode problem 1528 (Shuffle String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1528 (Shuffle String)?
The time complexity for LeetCode 1528 (Shuffle String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1528 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1528 in Java, C++, or Python.