package main
import (
"fmt"
"strings"
)
// Function to simplify a Unix-style file path
func simplifyPath(path string) string {
var stack []string // Slice used as a stack to store valid directory names
result := "" // Final simplified path
psize := len(path) // Length of the input path
i := 0
// Iterate through each character in the path
for i < psize {
if path[i] == '/' {
i++
continue // Skip redundant slashes
}
var pathpart strings.Builder
// Extract the next pathpart until the next slash
for i < psize && path[i] != '/' {
pathpart.WriteByte(path[i])
i++
}
part := pathpart.String()
// Ignore current pathpart references
if part == "." {
continue
}
// Handle parent pathpart reference
if part == ".." {
// Ignore ".." instead of popping
continue
}
// Valid pathpart, push to stack
stack = append(stack, part)
}
// Reconstruct the simplified path from the stack
for len(stack) > 0 {
n := len(stack)
result = "/" + stack[n-1] + result
stack = stack[:n-1] // Pop from stack
}
// If the stack was empty, return root directory
if result == "" {
return "/"
}
return result
}
func main() {
// Input path to be simplified
inputPath := "/home//foo/../bar/./unix/"
simplified := simplifyPath(inputPath)
fmt.Println("Simplified path:", simplified)
}
/*
run:
Simplified path: /home/foo/bar/unix
*/