Algorithm - LeetCode Problems 10

이소라·2023년 9월 19일
0

Algorithm

목록 보기
60/77

Problem 232. Implement Queue using Stacks

  • Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).

  • Implement the MyQueue class:

    • void push(int x) Pushes element x to the back of the queue.
    • int pop() Removes the element from the front of the queue and returns it.
    • int peek() Returns the element at the front of the queue.
    • boolean empty() Returns true if the queue is empty, false otherwise.
  • Notes:

    • You must use only standard operations of a stack, which means only push to top, peek/pop from top, size, and is empty operations are valid.
    • Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.

Example

  • Example 1:
    • Input
      • ["MyQueue", "push", "push", "peek", "pop", "empty"][], [1], [2], [], [], []]
    • Output
      • [null, null, null, 1, 1, false]
    • Explanation
      • MyQueue myQueue = new MyQueue();
      • myQueue.push(1); // queue is: [1]
      • myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
      • myQueue.peek(); // return 1
      • myQueue.pop(); // return 1, queue is [2]
      • myQueue.empty(); // return false

Constraints

  • 1 <= x <= 9
  • At most 100 calls will be made topush, pop, peek, and empty.
  • All the calls to pop and peek are valid.

Solution

var MyQueue = function() {
    this.queue = [];
};

/** 
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function(x) {
    this.queue.push(x);
};

/**
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    return this.queue.shift();
};

/**
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    return this.queue[0];
};

/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    return this.queue.length === 0;
};

/** 
 * Your MyQueue object will be instantiated and called as such:
 * var obj = new MyQueue()
 * obj.push(x)
 * var param_2 = obj.pop()
 * var param_3 = obj.peek()
 * var param_4 = obj.empty()
 */



Problem 946. Validate Stack Sequences

  • Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise.

Examples

  • Example 1:

    • Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
    • Output: true
    • Explanation: We might do the following sequence:
      • push(1), push(2), push(3), push(4),
      • pop() -> 4,
      • push(5),
      • pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
  • Example 2:

    • Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
    • Output: false
    • Explanation: 1 cannot be popped before 2.

Constraints:

  • 1 <= pushed.length <= 1000
  • 0 <= pushed[i] <= 1000
  • All the elements of pushed are unique.
  • popped.length == pushed.length
  • popped is a permutation of pushed.

Solution

  • 내 풀이
    • popped 배열을 기준으로 for 문을 돌면서 popped 배열 요소와 stack의 마지막 요소가 같지 않으면, pushed 배열의 인덱스를 증가시키면서 stack에 넣어줌
    • stack의 길이가 0인지 판별하여 true / false를 반환함
/**
 * @param {number[]} pushed
 * @param {number[]} popped
 * @return {boolean}
 */
var validateStackSequences = function(pushed, popped) {
    const stack = [pushed[0]];
    let pushedIndex = 1;

    for (const poppedNumber of popped) {
        while (pushedIndex < pushed.length && poppedNumber !== stack[stack.length - 1]) {
            stack.push(pushed[pushedIndex]);
            pushedIndex++;
        }
        if (poppedNumber === stack[stack.length - 1]) {
            stack.pop();
        }
    }

    return stack.length === 0;
};
  • 다른 사람 풀이
    • pushed 배열을 기준으로 for 문을 돌면서 pushed 배열 요소를 stack에 넣어주고, stack의 마지막 요소와 popped 배열 요소가 같다면 인덱스를 증가시키면서 stack을 pop함
    • popped 배열의 최종 인덱스가 pushed 길이와 같은지 판별하여 true/flase를 반환함
var validateStackSequences = function(pushed, popped) {
  const stack = [];
  let poppedIndex = 0;
  
  for (const pushedNumber of pushed) {
    stack.push(pushedNumber);
    while (stack.length && stack[stack.length - 1] === popped[poppedIndex]) {
      stack.pop();
      poppedIndex++;
    }
  }
  
  return pushed.length === poppedIndex;
}



Problem 1047. Remove All Adjacent Duplicates In String

  • You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.

We repeatedly make duplicate removals on s until we no longer can.

Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.

Example

  • Example 1:

    • Input: s = "abbaca"
    • Output: "ca"
    • Explanation:
      • For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".
  • Example 2:

    • Input: s = "azxxzy"
    • Output: "ay"

Constraints

  • 1 <= s.length <= 10^5
  • s consists of lowercase English letters.

Solution

/**
 * @param {string} s
 * @return {string}
 */
var removeDuplicates = function(s) {
    const stack = [];

    for (let i = 0; i < s.length; i++) {
        const str = s[i];
        if (stack.length && stack[stack.length - 1] === str) {
            stack.pop();
        } else {
            stack.push(str);
        }
    }

    return stack.join('');
};

0개의 댓글