[LeetCode] Crawler Log Folder

준규·2023년 1월 6일
0

1.문제


The Leetcode file system keeps a log each time some user performs a change folder operation.

The operations are described below:

  • "../" : Move to the parent folder of the current folder. (If you are already in the main folder, remain in the same folder).
  • "./" : Remain in the same folder.
  • "x/" : Move to the child folder named x (This folder is guaranteed to always exist).

You are given a list of strings logs where logs[i] is the operation performed by the user at the ith step.

The file system starts in the main folder, then the operations in logs are performed.

Return the minimum number of operations needed to go back to the main folder after the change folder operations.


파일 이동 log가 들어있는 logs 배열이 주어질 때 파일 이동은 다음과 같인 한다고 한다.

  • '../' : 한 단계 상위 폴더로 이동 (main 위치이면 그대로 있는다)
  • './' : 현재 폴더에 있는다.
  • 'x/' : x 자식 폴더로 이동한다.

처음에 main에 위치한다고 할 때 logs 배열 값대로 폴더이동을 한 후 다시 main 위치로 돌아가기 위해 취해야하는 상위 폴더 이동의 최소 횟수를 구하는 문제이다.


Example 1

Input: logs = ["d1/","d2/","../","d21/","./"]
Output: 2
Explanation: Use this change folder operation "../" 2 times and go back to the main folder.

Example 2

Input: logs = ["d1/","d2/","./","d3/","../","d31/"]
Output: 3

Example 3

Input: logs = ["d1/","../","../","../"]
Output: 0

Constraints:

  • 1 <= logs.length <= 10^3
  • 2 <= logs[i].length <= 10
  • logs[i] contains lowercase English letters, digits, '.', and '/'.
  • logs[i] follows the format described in the statement.
  • Folder names consist of lowercase English letters and digits.

2.풀이

  1. stack에 만약 현재 log가 폴더 이동이라면 새롭게 값을 넣어준다.
  2. 현재 log 값이 '../'이라면 stack의 top 값을 빼준다.
  3. stack의 길이가 main으로 가기위해 취해야할 폴더 이동 연산의 횟수이다.

/**
 * @param {string[]} logs
 * @return {number}
 */
const minOperations = function (logs) {
  const stack = [];

  for (let i = 0; i < logs.length; i++) {
    let top = stack[stack.length - 1];

    if (logs[i] === "../") {
      // '../' 이면 stack pop
      stack.pop();
    } else if (logs[i] === "./") {
      // './' 이면 폴더 이동 x
      continue;
    } else {
      // 폴더이동을 한다.
      stack.push(logs[i]);
    }
  }

  return stack.length; // stack의 길이 만큼 '../' 을 수행해야한다.
};

3.결과

profile
안녕하세요 :)

0개의 댓글