Leetcode: Shuffle String (Kotlin)
Leetcode: Shuffle String (Kotlin)
Shuffle String is an easy String and array problem on Leetcode. It gives you a shuffled string and a list of the indices where each character should be. I will discuss the approach I took to solve it. Shuffle String - LeetCode
Problem Statement
Examples
Constraints
Brainstorm
The way I thought of solving this was pretty straight forward.
-
First, create a character array from the string and also an empty character array that is the same size as the string.
-
Next, we can loop through our shuffled char array. Within each iteration, we will get the correct index from the indices array. We will use the correct index to figure where to store the current character in our blank character array
-
I can then pass the new restored array to the String constructor and return that
Solution
{% gist https://gist.github.com/cmcoffeedev/b5b9bb3a7f46cf684910eab228ac17e0.js %} You could get rid of the sArray and loop through the string this way:
s.forEachIndexed{ index, currentChar ->
val correctIndex = indices[index]
restored[correctIndex] = currentChar
}