Leetcode 1598. Crawler Log Folder

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Crawler Log Folder

2. Solution

解析:Version 1,使用数据结构栈,依次处理日志操作即可,最后栈中的元素数量即为当前在第几层子目录,因此返回根目录的次数为栈的长度。

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def minOperations(self, logs: List[str]) -> int:
stack = []
for log in logs:
if log == './':
continue
elif log == '../':
if stack:
stack.pop()
else:
stack.append(log)
return len(stack)

解析:Version 2,思想与1一样,直接计数即可。

  • Version 2
1
2
3
4
5
6
7
8
9
10
11
class Solution:
def minOperations(self, logs: List[str]) -> int:
count = 0
for log in logs:
if log == './':
continue
elif log == '../':
count = max(0, count - 1)
else:
count += 1
return count

Reference

  1. https://leetcode.com/problems/crawler-log-folder/
如果有收获,可以请我喝杯咖啡!