zoukankan      html  css  js  c++  java
  • [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是一串操作inputs,请你返回的是返回主文件夹(根目录)所需的最小步数。

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

    如果这个题问你如何不使用额外空间怎么做,可以参考844题,反向扫描。

    时间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 }

    相关题目

    844. Backspace String Compare

    1598. Crawler Log Folder

    LeetCode 题目总结

  • 相关阅读:
    grep
    Ubuntu配置sun jdk
    mysqldump导出数据库表结构与数据至本地
    checkbox前后台使用
    MAC OS X 命令行提交本地项目到git
    前端参数传递错误之中英文字符
    微信支付之扫码支付(java版 native原生支付)
    jquery 取消 radio checked 属性,重新选中的问题解决
    消除父级元素对子级元素的点击事件影响
    mysql 双机热备注意事项
  • 原文地址:https://www.cnblogs.com/cnoodle/p/13738680.html
Copyright © 2011-2022 走看看