Skip to content

Commit 399f496

Browse files
authored
Update Shuffle String.java
1 parent 06b495b commit 399f496

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

Easy/Shuffle String.java

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,24 @@
11
class Solution {
22
public String restoreString(String s, int[] indices) {
3-
char[] letters = new char[s.length()];
3+
char[] letters = s.toCharArray();
44
for (int i = 0; i < indices.length; i++) {
5-
letters[indices[i]] = s.charAt(i);
5+
while (indices[i] != i) {
6+
swapLetter(letters, i, indices[i]);
7+
swapIndex(indices, i, indices[i]);
8+
}
69
}
710
return String.valueOf(letters);
811
}
12+
13+
private void swapLetter(char[] arr, int idxOne, int idxTwo) {
14+
char temp = arr[idxOne];
15+
arr[idxOne] = arr[idxTwo];
16+
arr[idxTwo] = temp;
17+
}
18+
19+
private void swapIndex(int[] arr, int idxOne, int idxTwo) {
20+
int temp = arr[idxOne];
21+
arr[idxOne] = arr[idxTwo];
22+
arr[idxTwo] = temp;
23+
}
924
}

0 commit comments

Comments
 (0)