From 65da0147fee323b9acf951fe7dc6099798a486e5 Mon Sep 17 00:00:00 2001 From: ShusenTang Date: Mon, 23 Dec 2019 16:31:51 +0800 Subject: [PATCH] Create 388. Longest Absolute File Path.md --- solutions/388. Longest Absolute File Path.md | 43 ++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 solutions/388. Longest Absolute File Path.md diff --git a/solutions/388. Longest Absolute File Path.md b/solutions/388. Longest Absolute File Path.md new file mode 100644 index 0000000..8a3fe8c --- /dev/null +++ b/solutions/388. Longest Absolute File Path.md @@ -0,0 +1,43 @@ +# [388. Longest Absolute File Path](https://leetcode.com/problems/longest-absolute-file-path/) +# 思路 +这道题给了我们一个字符串,里面包含 \n 和 \t 这种表示回车和空格的特殊字符,让我们找到某一个最长的绝对文件路径。 + +我们可以从前往后遍历输入字符串,用一个数组记录每一层文件夹的绝对路径长度,用一个tag来标记是否是文件(一旦遇到了'.'就是文件), +用变量depth记录当前文件(夹)的层次(有多少'\t'就有多深)。 + + +# C++ +``` C++ +class Solution { +public: + int lengthLongestPath(string input) { + int l = 0, r = 0, depth = 0, res = 0, input_size = input.size(); + vectordir_lens; + bool file_tag = false; + while(r <= input_size){ + if(r == input_size || input[r] == '\n'){ //遇到换行符, 处理r之前的 + if(!file_tag){ // 是个dir + // 加1是因为 xxx/xxx/ 里面的斜杠 + int tmp = 1 + r - l + (depth == 0 ? 0: dir_lens[depth - 1]); + if(dir_lens.size() == depth) dir_lens.push_back(tmp); + else dir_lens[depth] = tmp; + } + else res = max(res, r - l + (depth == 0 ? 0: dir_lens[depth - 1])); + + depth = 0; file_tag = false; // 初始化 + while(r + 1 < input_size && input[r+1] == '\t') { + r += 1; + depth += 1; // 有多少'\t'就有多深 + } + + l = r + 1; + } + else if(r < input_size && input[r] == '.') file_tag = true; + + r++; + } + + return res; + } +}; +```