LeetCode 1598: Crawler Log Folder

ArrayStringStack

Problem Description

Explanation

To solve this problem, we can simulate the operations described in the logs and keep track of the current folder. We can use a stack data structure to represent the current directory structure. If we encounter "../", we pop from the stack to move to the parent folder. If we encounter "./", we stay in the same folder. If we encounter a folder name, we push it onto the stack to move to the child folder.

Algorithm

  1. Initialize an empty stack to represent the current directory structure.
  2. Iterate through each operation in the logs.
  3. If the operation is "../", pop from the stack if it's not empty (to move to the parent folder).
  4. If the operation is "./", do nothing (stay in the same folder).
  5. If the operation is a folder name, push it onto the stack (to move to the child folder).
  6. Finally, return the size of the stack (the number of operations needed to go back to the main folder).

Time Complexity

The time complexity of this algorithm is O(n) where n is the number of operations in the logs.

Space Complexity

The space complexity of this algorithm is O(n) where n is the number of operations in the logs.

Solutions

class Solution {
    public int minOperations(String[] logs) {
        Stack<String> stack = new Stack<>();
        
        for (String log : logs) {
            if (log.equals("../")) {
                if (!stack.isEmpty()) {
                    stack.pop();
                }
            } else if (!log.equals("./")) {
                stack.push(log);
            }
        }
        
        return stack.size();
    }
}

Loading editor...