1 minute read

Day10

스택

  • 문제 : 올바른 괄호
  • 정답코드
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    
    function solution(s) {
      let count = 0;
        
      for(const c of s) {
          if (c === '(') {
              count++;
          } else {
              if (count === 0) {
                  return false;
              }
              count -= 1;
          }
      }
        
      return count === 0;
    }
    

  • 문제 : 프린터
  • 정답코드 ```javascript class Node { constructor(value) { this.value = value; this.next = null; } }

class Queue { constructor() { this.head = null; this.tail = null; }

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
size() {
    let i = 0;
    let node = this.head;
    while (node) {
        node = node.next;
        i++;
    }
    return i;
}

enqueue(newValue) {
    const newNode = new Node(newValue);
    if (this.head === null) {
        this.head = this.tail = newNode;
    } else {
        this.tail.next = newNode;
        this.tail = newNode;
    }
}

dequeue() {
    const value = this.head.value;
    this.head = this.head.next;
    return value;
}

peek() {
    return this.head.value;
} }

function solution(priorities, location) { const queue = new Queue(); for (let i = 0; i < priorities.length ; i++) { queue.enqueue([priorities[i], i]); }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
priorities.sort((a,b) => b-a);

let count = 0;
while (queue.size() > 0) {
    const currentValue = queue.peek();
    if (currentValue[0] < priorities[count]) {
        queue.enqueue(queue.dequeue());
    } else {
        const value = queue.dequeue();
        count += 1;
        if (location === value[1]) {
            return count;
        }
    }
}

return count; } ```

Categories:

Updated: