알고리즘 풀이/프로그래머스

[프로그래머스][JAVA] 표 편집 (Node)

배게 2021. 9. 11. 13:36
728x90

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import java.util.*;
 
class Solution {
    class Node{
        boolean removed;
        Node prev;
        Node next;
        
    }
    
    Node[] NodeArr = new Node[1000000];
    
    public String solution(int n, int k, String[] cmd) {
        for(int i=0; i<n; i++){
            NodeArr[i] = new Node();
        }
        
        for(int i=1; i<n; i++){
            NodeArr[i-1].next=NodeArr[i];
            NodeArr[i].prev=NodeArr[i-1];
        }
        
        Node curr = NodeArr[k];
        Stack<Node> mystack = new Stack<>();
        
        for(String str : cmd){
            if(str.charAt(0)=='U'){
                int x = Integer.parseInt(str.substring(2));
                for(int i=0; i<x; i++){
                    curr=curr.prev;
                }
                
            }else if(str.charAt(0)=='D'){
                int x = Integer.parseInt(str.substring(2));
                for(int i=0; i<x; i++){
                    curr=curr.next;
                }
                
            }else if(str.charAt(0)=='C'){
                mystack.push(curr);
                curr.removed = true;
                Node up = curr.prev;
                Node down = curr.next;
                if(up!=null){
                    up.next = down;
                }
                if(down!=null){
                    down.prev = up;
                    curr = down;
                } else{
                    curr = up;
                }
                
                
                
            }else if(str.charAt(0)=='Z'){
                Node node = mystack.pop();
                node.removed = false;
                Node up = node.prev;
                Node down = node.next;
                if(up!=null)
                    up.next = node;
                if(down!=null)
                    down.prev = node;
            }
            
        }
        
        
        
        
        
        StringBuilder answer = new StringBuilder();
        for(int i=0; i<n; i++){
            if(NodeArr[i].removed){
                answer.append('X');
            }
            else
                answer.append('O');
            
        }
        
        return answer.toString();
    }
}
cs