Suppose we abstract our file system by a string in the following manner:
The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext"
represents:
dir subdir1 subdir2 file.ext
The directory dir
contains an empty sub-directory subdir1
and a sub-directory subdir2
containing a file file.ext
.
The string "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"
represents:
dir subdir1 file1.ext subsubdir1 subdir2 subsubdir2 file2.ext
The directory dir
contains two sub-directories subdir1
and subdir2
. subdir1
contains a file file1.ext
and an empty second-level sub-directory subsubdir1
. subdir2
contains a second-level sub-directory subsubdir2
containing a file file2.ext
.
We are interested in finding the longest (number of characters) absolute path to a file within our file system. For example, in the second example above, the longest absolute path is"dir/subdir2/subsubdir2/file2.ext"
, and its length is 32
(not including the double quotes).
Given a string representing the file system in the above format, return the length of the longest absolute path to file in the abstracted file system. If there is no file in the system, return 0
.
Note:
- The name of a file contains at least a
.
and an extension. - The name of a directory or sub-directory will not contain a
.
.
Time complexity required: O(n)
where n
is the size of the input string.
Notice that a/aa/aaa/file1.txt
is not the longest file path, if there is another path aaaaaaaaaaaaaaaaaaaaa/sth.png
.
题意里已经说明了并不是最”深层“的文件就是路径名最长的。
看一下例子,例如path="dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"
因为目录是具有层次结构的,体现在给定的字串里面:每个第K层的目录之前一定会有一个K-1层的目录出现
可以使用栈来解,栈记录的内容是上一次目录名称的长度。把字串按照“\n”分割之后来考虑,前导的"\t"表明层次,有1个"\t"表明在第二层,有K个“\t”表明在K+1层。扫描一个分割后的子字串的时候根据"\t"的个数得到层数C,如果比当前层数大,则把上一层目录长度压栈并且进入第C层;如果刚好等于当前层数,则不需要对栈进行操作;如果小于当前层数,则弹栈直到第C层。
长度的计算:当前扫描的子字串长度+当前栈中所有元素的长度(所有上级目录长度和)+额外添加的斜杠 即为路径的长度
public class Solution {
public static int lengthLongestPath(String input)
{
if(input.indexOf(".")==-1)
return 0;
Stack<Integer> stack=new Stack<>();
String[] strs=input.split("\n");
int lastlen=0;
int max=0;
int curStep=0;
for(String s : strs)
{
int i=0;
while(i+1<s.length()&&s.charAt(i)=='\t')
i++;
int curlen=s.length();
if(i>curStep)
{
curStep++;
stack.push(lastlen);
}
else if(i<curStep)
{
while(i<curStep)
{
stack.pop();
curStep--;
}
}
curlen-=i;
int sum=0;
if(s.indexOf(".")!=-1)
{
for(int num :stack)
sum+=(num+1);
sum+=curlen;
}
lastlen=curlen;
max=Math.max(max, sum);
}
return max;
}
}