LeetCode/solutions/388. Longest Absolute File Path.md
2019-12-23 16:31:51 +08:00

44 lines
1.7 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [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();
vector<int>dir_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;
}
};
```