Java C++题解leetcode1598文件夹操作日志搜集器

题目要求

思路:模拟

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

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(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(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(1)

总结

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

作者:AnjaVon

%s 个评论

要回复文章请先登录注册