[LeetCode] 22.Shuffle String

2021. 5. 25. 16:12

https://leetcode.com/problems/shuffle-string/

 

Shuffle String - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

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문을 만들지 말고 어떻게 하면 더 효율적으로 풀 수 있을지 생각하고 풀어야겠다.

 

BELATED ARTICLES

more