본문 바로가기

ProgramSoliving

프로그래머스 : 표 편집 (JavaScript)

반응형

https://programmers.co.kr/learn/courses/30/lessons/81303

 

코딩테스트 연습 - 표 편집

8 2 ["D 2","C","U 3","C","D 4","C","U 2","Z","Z"] "OOOOXOOO" 8 2 ["D 2","C","U 3","C","D 4","C","U 2","Z","Z","U 1","C"] "OOXOXOOO"

programmers.co.kr

JavaSciprt로 양방향 연결리스트 구현 후 처리해주면 쉽게 풀 수 있습니다.

var list;
var stack = [];
var answer;

const Delete = (k) => {
    stack.push([k,list[k][0],list[k][1]]);
    let pre = list[k][0];
    let next = list[k][1];
    
    answer[k] = false;
    
    if(next === -1){
        if(pre !== -1)
            list[pre][1] = next;
        k = pre;
    }else{
        if(next !== -1)
            list[next][0] = pre;
        if(pre !== -1)
            list[pre][1] = next;
        k = next;
    }
    
    return k;
};

const Down = (k,m) => {
    for(let i=0;i<m;i++)
        k = list[k][1];
    return k;
        
};

const Up = (k,m) => {
    for(let i=0;i<m;i++)
        k = list[k][0];
    return k;
};

const GetBack = () => {
    const s = stack.pop();
    const k = s[0];
    const pre = s[1];
    const next = s[2];
    
    if(pre !== -1)
        list[pre][1] = k;
    if(next !== -1)
        list[next][0] = k;
    
    answer[k] = true;
};

function solution(n, k, cmd) {
    // LinkedList
    list = Array.from({length: n}, (value,index) => ([index-1, index+1]));
    answer = Array(n).fill(true);
    list[n-1][1] = -1;                      
    for(let c of cmd) {
        let order = c.split(' ');
        
        switch(order[0]){
            //down 
            case 'D':
                k = Down(k,order[1]);
            break;
            //delete
            case 'C':
                k = Delete(k);
            break;
            // up
            case 'U':
                k = Up(k,order[1]);
            break;
            // privious
            case 'Z':
                GetBack();
            break;
        }
    }
    
    var ret = [];
    for(let i=0;i<n;i++){
        if(answer[i]){
            ret.push('O');
        }else{
            ret.push('X');
        }
    }
    
    return ret.join('');
}
반응형