likes
comments
collection
share

Java&C++题解与拓展——leetcode1598.文件夹操作日志搜集器【么的新知识】

作者站长头像
站长
· 阅读数 13
每日一题做题记录,参考官方和三叶的题解

题目要求

Java&C++题解与拓展——leetcode1598.文件夹操作日志搜集器【么的新知识】

Java&C++题解与拓展——leetcode1598.文件夹操作日志搜集器【么的新知识】

思路:模拟

  • 根据日志判断目前在哪一级子文件夹即可,级数就等于返回时的步数,主文件夹级数初始为000
    • xl:级数+1+1+1
    • ./:级数不变;
    • ../:级数−1-11

Java

class Solution {
    public int minOperations(String[] logs) {
        int res = 0;
        for (String l : logs) {
            if (l.equals("../")) // 返回父级
                res = Math.max(0, res - 1);
            else if (!l.equals("./")) // 向下进入
                res++;
        }
        return res;
    }
}
  • 时间复杂度:O(n)O(n)O(n)
  • 空间复杂度:O(1)O(1)O(1)

C++

class Solution {
public:
    int minOperations(vector<string>& logs) {
        int res = 0;
        for (auto & l : logs) {
            if (l == "../") // 返回父级
                res = max(0, res - 1);
            else if (l != "./") // 向下进入
                res++;
        }
        return res;
    }
};
  • 时间复杂度:O(n)O(n)O(n)
  • 空间复杂度:O(1)O(1)O(1)

Rust

impl Solution {
    pub fn min_operations(logs: Vec<String>) -> i32 {
        logs.into_iter().fold(0, |mut res, l| {
            if l == "../" { // 返回父级
                if res > 0 {
                    res -= 1;
                }
            }
            else if l != "./" { // 向下进入
                res += 1;
            }
            res
        })
    }
}
  • 时间复杂度:O(n)O(n)O(n)
  • 空间复杂度:O(1)O(1)O(1)

总结

超级简单模拟题【水了一篇】,不要考虑怎么回去,直接看怎么去的计算就可以了【又是逆向思维……】。

欢迎指正与讨论!