Leetcode388

摘要部分
388. 文件的最长绝对路径

#388. 文件的最长绝对路径

仔细阅读说明,审题很重要,文件名至少存在一个就说明这是非常重要的。而且返回的是文件的最长目录,所以maxlenth的更新一定是在文件出现的时候
题目中说到目录名中一定不存在.也是一个提示,应该很敏感的感受到这是关于栈的更新的。dfs需要回溯说明不符合题目中o(n)复杂度的要求。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def lengthLongestPath(self, input):
stack=[[-1,0]]
maxlenth=0
for i in input.split('\n'):
depth=i.count('\t')
this=i.replace('\t','')
while stack and depth<=stack[-1][0]:
stack.pop()
if '.' in i:
maxlenth=max(maxlenth,len(this)+stack[-1][1])
else:
stack.append([depth,stack[-1][1]+len(this)+1])
return maxlenth