본문 바로가기

LeetCode

1598. Crawler Log Folder / TypeScript

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.

 

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

 

출처:https://leetcode.com/problems/crawler-log-folder/description/

 

풀이

function minOperations(logs: string[]): number {
    return logs.reduce((a,c)=>{
        if(c==='../') return Math.max(0,a-1)
        if(c==='./') return a 
        return a+1
    },0)
};

 

필요한 최소 작업 횟수를 계산

 

  • reduce 메서드를 사용하여 배열 logs를 순회
  • reduce의 콜백 함수는 누적값 a와 현재 값 c를 인수로 받음
  • c가 '../'일 경우, 현재 디렉토리에서 한 단계 위로 이동하므로 a를 1 감소시키지만, a가 0보다 작아지지 않도록 Math.max(0, a-1)을 반환.
  • c가 './'일 경우, 현재 디렉토리에 머무르므로 a를 그대로 반환.
  • 이외의 경우에는 새로운 디렉토리로 이동하는 것을 의미하므로 a를 1 증가.
  • 초기값으로 0을 설정하여 시작