[LeetCode] 22.Shuffle String
https://leetcode.com/problems/shuffle-string/
1. Problem
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"
2. Code
-처음 풀이
package leetCode;
public class ShuffleString {
public static void main(String[] args) {
String s = "codeleet";
int[] indices = {4,5,6,7,0,2,1,3};
System.out.println(restoreString(s, indices));
}
public static String restoreString(String s, int[] indices) {
String result = "";
for(int i = 0; i < indices.length; i++) {
for(int j = 0 ; j < indices.length; j++) {
if(i == indices[j]) {
result += s.charAt(j) + "";
break;
}
}
}
return result;
}
}
- 수정 후
package leetCode;
public class ShuffleString {
public static void main(String[] args) {
String s = "codeleet";
int[] indices = {4,5,6,7,0,2,1,3};
System.out.println(restoreString(s, indices));
}
public static String restoreString(String s, int[] indices) {
char[] str = new char[indices.length];
for(int i = 0; i < indices.length; i++) {
str[indices[i]] = s.charAt(i);
}
return new String(str);
}
}
3. Report
처음에 푼 방식은 이중 for문을 이용한 방식이고 (faster 9%)
수정 후 방식은 for문을 한번만 이용할 수 있게 만든 풀이이다. (faster 99%)
무작정 이중 for문을 만들지 말고 어떻게 하면 더 효율적으로 풀 수 있을지 생각하고 풀어야겠다.
'Algorithm > 문제' 카테고리의 다른 글
[LeetCode] 24.Missing Number (0) | 2021.06.01 |
---|---|
[LeetCode] 23.Rotate String (0) | 2021.05.27 |
[Study] 21. 두개의 원 반경 안에 있는 좌표 값 찾기 (0) | 2021.03.02 |
[LeetCode] 20.Search Insert Position (0) | 2021.03.02 |
[Study] 19.최대 실행 횟수 구하기 (0) | 2021.01.26 |