mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 388. Longest Absolute File Path.md
This commit is contained in:
parent
33e2e788aa
commit
65da0147fe
43
solutions/388. Longest Absolute File Path.md
Normal file
43
solutions/388. Longest Absolute File Path.md
Normal file
@ -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();
|
||||
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;
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in New Issue
Block a user