C# version with explanations


  • 0
    G
    public static int LengthLongestPath(string input)
    {
    	if (string.IsNullOrEmpty(input))
    	{
    		return 0;
    	}
    	var result = 0;
    	var tokens = input.Split('\n');
    	var cache = new Dictionary<int, int>();
    	
    	foreach (var token in tokens)
    	{
    		var dummy = token.Replace("\t", string.Empty);
    		var level = token.Length - dummy.Length;
    
    		var upperLevelLength = 0;
    		if (level > 0)
    		{
    			upperLevelLength = cache[level - 1] + 1; // +1 for '/'
    		}
    		cache[level] = dummy.Length + upperLevelLength;
    
    		if (IsFile(token)) // update result only if it's a file
    		{
    			result = Math.Max(result, cache[level]);
    		}
    	}
    	
    	return result;
    }
    
    private static bool IsFile(string token)
    {
    	return token.Contains(".");
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.