공부, 알고리즘/LeetCode (리트코드)

[리트코드/JAVA] 1528. Shuffle String

박주단 2021. 4. 27. 22:13

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

# 문제설명

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.

 

# 제한사항

  • s.length == indices.length == n
  • 1 <= n <= 100
  • s contains only lower-case English letters.
  • 0 <= indices[i] < n
  • All values of indices are unique (i.e. indices is a permutation of the integers from 0 to n - 1).

# 입출력 예

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.

 

# 풀이

class Solution {
  public String restoreString(String s, int[] indices) {
    char[] arrChar = new char[indices.length];

    for(int i=0; i<indices.length; i++) {
    	arrChar[indices[i]] = s.charAt(i);
    }

    String output = String.valueOf(arrChar);
    
    return output;
  }
}

 

#3

char타입의 배열(arrChar)을 선언합니다.

 

#5~7

문자열 s를 하나씩 분리해서 indices배열의 인덱스 값에 맞춰서 재정렬합니다.

 

#9

char배열을 String으로 변환해서 리턴합니다.