Golang Solution


  • 0
    H
    func lengthLongestPath(input string) int {
    	parts := strings.Split(input, "\n")
    	currLen := 0
    	result := 0
    	stack := []int{}
    
    	for _, part := range parts {
    		currLevel := currentLevel(part)
    
    		// keep poping the stack until the level in the stack is matching with the level for the current part
    		for len(stack) > currLevel {
    			var top int
    			top, stack = stack[len(stack) - 1], stack[:len(stack) - 1]
    
    			currLen -= top
    		}
    
    		// +1 for the slash after each folder, such as sub1/sub2
    		partLen := len(strings.Replace(part, "\t", "", -1)) + 1
    		currLen += partLen
    
    		// we found a file, the current length becomes one candidate for the result
    		if strings.Contains(part, ".") {
    			// file doesn't have ending slash, so -1 for the current length
    			partLen -= 1
    			currLen -= 1
    			if currLen > result {
    				result = currLen
    			}
    		}
    
    		stack = append(stack, partLen)
    	}
    
    	return result
    }
    
    // for root level, returns 0
    func currentLevel(str string) int {
    	replaced := strings.Replace(str, "\t", "", -1)
    	return len(str) - len(replaced)
    }
    

Log in to reply
 

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