#1528
Shuffle String
Easy char[] basics
- Read
- Understand
- Hints
- Approach
- Solution
- Solved
?The problem
Character i of the string must move to position indices[i]. Return the rearranged string.
This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗
◎Understanding
Really asking: character i should end up at position indices[i].
Why this works: Strings can't be changed, so place characters into a char[] and turn it into a String at the end.
Example: s = "abc", indices = [2, 0, 1]
'a' → res[2]'b' → res[0]'c' → res[1]res = "bca"
✦Hints open one at a time
Create a char array of the same length.
Place s.charAt(i) at result[indices[i]], then build a String from the array.
↗Approach
Use a char[] as a writable buffer since Strings are immutable, then convert with new String(chars).
</>Solution (Java)
class Solution {
public String restoreString(String s, int[] indices) {
char[] res = new char[s.length()];
for (int i = 0; i < s.length(); i++) {
res[indices[i]] = s.charAt(i); // char i goes to indices[i]
}
return new String(res);
}
}
!Common mistake
Reading result[i] = s.charAt(indices[i]) — that applies the move in the wrong direction.
