[LeetCode] 1598. Crawler Log Folder

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

Constraints:

  • 1 <= logs.length <= 103
  • 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.

文件夹操作日志搜集器。

题意跟一般的文件夹之间的操作很像,包括"../", "./", "x/"三种方式,其中"x/"表示将进入一个文件夹,"../"表示回退一个层级,"./"表示原地不动。给的input是一串操作 logs,请你返回的是返回主文件夹(根目录)所需的最小步数。

思路是用 stack 记录每一步的行为。如果是"./"则跳过,如果是"x/"则将"x/"入栈,如果是"../"且stack不为空,则从 stack 弹出一个元素。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public int minOperations(String[] logs) {
 3         // corner case
 4         if (logs == null || logs.length == 0) {
 5             return 0;
 6         }
 7         // normal case
 8         Stack<String> stack = new Stack<>();
 9         System.out.println(stack.size());
10         for (int i = 0; i < logs.length; i++) {
11             if (logs[i].equals("../")) {
12                 if (!stack.isEmpty()) {
13                     stack.pop();
14                 }
15             } else if (logs[i].equals("./")) {
16                 continue;
17             } else {
18                 stack.push(logs[i]);
19             }
20         }
21         return stack.isEmpty() ? 0 : stack.size();
22     }
23 }

 

还有一种做法就是直接扫描,用一个变量 depth 记录文件夹的深度。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public int minOperations(String[] logs) {
 3         int depth = 0;
 4         for (String log : logs) {
 5             if (log.equals("../")) {
 6                 if (depth > 0) {
 7                     depth--;
 8                 }
 9             } else if (Character.isLetterOrDigit(log.charAt(0))) {
10                 depth++;
11             }
12         }
13         return depth;
14     }
15 }

 

相关题目

844. Backspace String Compare

1598. Crawler Log Folder

LeetCode 题目总结

posted @ 2020-09-27 12:17  CNoodle  阅读(392)  评论(0编辑  收藏  举报