[LeetCode] 1528. Shuffle String
Coding Test

[LeetCode] 1528. Shuffle String

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 ith 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" Explanation: As shown, "codeleet" becomes "leetcode" after shuffling.
Example 2:
Input: s = "abc", indices = [0,1,2] Output: "abc" Explanation: After shuffling, each character remains in its position.
Example 3:
Input: s = "aiohn", indices = [3,1,4,2,0] Output: "nihao"
Example 4:
Input: s = "aaiougrt", indices = [4,0,2,6,7,3,1,5] Output: "arigatou"
Example 5:
Input: s = "art", indices = [1,0,2] Output: "rat"

문자열과 문자의 순서가 주어졌을 때 문자를 다시 정렬하는 문제입니다.

 

처음에는 Map을 생성하여 문제를 해결 하려고 했는데요. 간략하게 Map<Integer, String>으로 문자가 위치 해야 할 index와 해당 문자를 put 해주었고 key 기준으로 정렬하였습니다. 하지만 실행 속도가 매우 느렸네요.

 

고민하던 중 간단하게 array 배열을 하나 똑같이 생성해서 넣어주기로 했습니다. 속도상 이 방법이 훨씬 빠르겠네요.

코드는 다음과 같습니다.

 

public String restoreString(String s, int[] indices) {
  char[] tmp = s.toCharArray();
  for (int i = 0; i < s.length(); i++) {
  	tmp[indices[i]] = s.charAt(i);
  }
  return String.valueOf(tmp);
}

매우 간단하게 해결이 되는군요. 다음은 결과입니다.

처음에는 약 5% 보다 빠른 결과가 나왔었습니다. 속도를 생각하여 더욱 단순히 가야 하는것이 옳겠습니다.

감사합니다.