LeetCode 코딩 문제 2021/07/09 - Shuffle String

이호현·2021년 7월 9일
0

Algorithm

목록 보기
126/138

[문제]

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"

(요약) 주어진 숫자 배열의 위치를 index로 생각하고 문자열을 재배치하라.

[풀이]

var restoreString = function(s, indices) {
  const arr = indices.map((n, idx) => {
    return { index: n, char: s[idx] };
  });
   
  return arr.sort((a, b) => {
    return a.index - b.index;
  }).map(el => el.char).join('')
};

우선 문자열과 배열 숫자를 객체로 묶는다.

[{ index: 1, char: 'a' },{ index: 2, char: 'b' },{ index: 0, char: 'c' }] 이런 식으로 만든다.

그 다음 각 객체의 숫자가 index이니 그걸 기준으로 오름차순 정렬을 한다.

마지막으로 문자열만 뽑아서 return.

var restoreString = function(s, indices) {
  const length = indices.length;
  const result = new Array(length).fill('');
   
  for(let i = 0; i < length; i++) {
    result[indices[i]] = s[i];
  }
   
  return result.join('');
};

두 번째 방법은 미리 주어진 배열 크기만큼의 배열을 만든다.

그 다음에 sindices는 길이가 같으니 처음 요소부터 돌면서 result의 해당 인덱스에 문자열을 넣는 방법이다.

예를 들어 'abc', [1, 2, 0]으로 주어지면 ['', '', '']를 먼저 만들고,
a는 만들어진 배열의 1번째 인덱스,
b는 만들어진 배열의 2번째 인덱스
c는 만들어진 배열의 0번째 인덱스
에 넣으면 ['c', 'a', 'b']가 된다.

profile
평생 개발자로 살고싶습니다

0개의 댓글