Problem: Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture:
Example:
Input: input = "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" Output: 20 Explanation: We have only one file, and the absolute path is "dir/subdir2/file.ext" of length 20.
Approach: If you see it looks like a tree. To get the maximum path length, you need to do DFS to get all the paths and return the path which has the longest length. I am doing the same without making the tree. My approach performed better than 98.53% of C# submissions.
Implementation in C#:
public static int LengthLongestPath(string input)
{
string[] paths = input.Split('\n');
int maxPathLength = 0;
List<int> pathLengths = new List<int>();
for (int i = 0; i < paths.Length; ++i)
{
int count = paths[i].Count(ch => ch == '\t');
if (count > pathLengths.Count - 1)
{
if (count == 0)
{
pathLengths.Add(paths[i].Length);
}
else
{
pathLengths.Add(paths[i].Substring(paths[i].LastIndexOf('\t') + 1).Length + pathLengths[count - 1] + 1);
}
}
else
{
if (count == 0)
{
pathLengths[count] = paths[i].Length;
}
else
{
pathLengths[count] = paths[i].Substring(paths[i].LastIndexOf('\t') + 1).Length + pathLengths[count - 1] + 1;
}
}
if (paths[i].Contains('.'))
{
maxPathLength = Math.Max(maxPathLength, pathLengths[count]);
}
}
return maxPathLength;
}
Complexity: ?
No comments:
Post a Comment