Problem Link: https://leetcode.com/problems/longest-absolute-file-path/
Note:
This problem intuitively resembles a tree structure. But it can be solved using a deque easily, though I think the first data structure that will come to mind is a stack, at least that was in my case. A stack would work, but eventually while accessing all the elements of the stack for length counting, then you will get how deque will serve in that case!
In the following code, one limiting criterion is that the length of the level cannot be less than the size of the deque, if it is greater then we have already processed the subdirectory/file and we haven’t found our answer yet, so we can discard that from the deque.
class Solution {
public:
int lengthLongestPath(string input) {
deque<int> dq;
int len=0, level=0, res=0;
bool flag=0;
for(int i=0; i<input.size(); i++)
{
if(input[i]=='\n')
{
dq.push_back(len);
len=0;
level=0;
flag=0;
}
else if(input[i]=='\t') level++;
else if(input[i]=='.')
{
flag=1;
len++;
}
else
{
len++;
if(flag)
{
int sum=0;
for(int i=0; i<dq.size(); i++)
{
sum+=dq[i];
}
res=max(res, sum+len+level);
}
while(level<dq.size()) dq.pop_back();
}
}
return res;
}
};
One thought on “LeetCode 388. Longest Absolute File Path”