388. The longest absolute path of the file
We assume in the following manner our abstract file system into a string:
String "dir \ n \ tsubdir1 \ n \ tsubdir2 \ n \ t \ tfile.ext" represents:
dir
subdir1
subdir2
file.ext
Dir directory contains an empty subdirectory contains a subdirectory subdir2 subdir1 and file.ext of a file.
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
Dir directory contains two subdirectories subdir1 and subdir2. subdir1 file1.ext file contains a secondary air and a subdirectory subsubdir1. subdir2 subdirectory contains a two subsubdir2, which contains a file file2.ext.
We are committed to looking up our file system files (according to statistics the number of characters) absolute path. For example, in the above second example, the longest path of "dir / subdir2 / subsubdir2 / file2.ext", its length is 32 (without quotation marks).
Given a string that represents the file system in the format described above, returns the length of the longest absolute path of the file in the file system. If the system does not file returns 0.
Description:
At least one file name. And an extension.
Directory or subdirectory name can not contain ..
Required time complexity is O (n), where n is the size of the input string.
Please note that if there is a path aaaaaaaaaaaaaaaaaaaaa / sth.png, then a / aa / aaa / file1.txt is not one of the longest path.
PS:
"\ t is a character."
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Solution {
//bx
public int lengthLongestPath(String input) {
if (input.length() == 0) {
return 0;
}
int res = 0;
String[] dirs = input.split("\n");
int[] sum = new int[dirs.length+1];
//StringBuilder sb = new StringBuilder();
for (String s : dirs) {
int level = s.lastIndexOf('\t') + 2;
//if (level == 2){
//sb.setLength(sum[1]);
//}
//sb.append(s.substring(s.lastIndexOf("\t")+1));
int len = s.length() - (level - 1);
if (s.contains(".")) {
res = Math.max(res, sum[level - 1] + len);
} else {
sum[level] = sum[level - 1] + len + 1; //是目录,要+1,目录有个/的
//sb.append("\\");
}
}
//System.out.println(sb.toString());
return res;
}
}