[Leetcode] 1528. Shuffle String (JS)

OROSY·2021년 4월 28일
0

Algorithms

목록 보기
9/38
post-thumbnail

출처

Leetcode 1528. Shuffle String

문제

나의 코드

오래 고민해서 루프 안에 루프로 풀이를 해서 결과는 나쁘지 않지만 역시나 다른 분들의 코드를 보면 나의 코드는 사소해 보이는 마법

1
2
3
4
5
6
7
8
9
10
11
var restoreString = function(s, indices) {
    let sorted = ''
    for (i = 0; i < indices.length; i++) {
        for (j = 0; j < indices.length; j++) {
            if(indices[j] === i) {
                sorted += s[j]
            }
        }
    }
    return sorted;
};
cs

다른 코드

생성자 함수로 길이가 4인 새로운 배열을 생성하고 모든 값이 undefined이기 때문에 s의 배열 값을 하나씩 넣는 풀이 방법.. 놀랍다 ㄷㄷ

1
2
3
4
5
6
7
8
var restoreString = function(s, indices) {
    var len = indices.length;
    var str = new Array(len);     
    for(let i=0; i<len;i++){
        str[indices[i]] = s[i];
    }
    return str.join("");  
};
cs

실행 결과

profile
Life is a matter of a direction not a speed.

0개의 댓글