71.go 619 B

123456789101112131415161718192021222324252627282930313233343536
  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. func simplifyPath(path string) string {
  7. strs := strings.Split(path, "/")
  8. res := []string{""}
  9. for _, v := range strs {
  10. // "/./" or "//" => ""
  11. if v == "." || v == "" {
  12. } else if v == ".." {
  13. // "/../" => "/"
  14. // "/d/c/../" => "/d"
  15. if len(res) != 1 {
  16. res = res[:len(res)-1]
  17. }
  18. } else {
  19. // "/c" => "/c"
  20. res = append(res, v)
  21. }
  22. }
  23. // "" => "/"
  24. if len(res) == 1 {
  25. return "/"
  26. }
  27. return strings.Join(res, "/")
  28. }
  29. func main() {
  30. fmt.Println(simplifyPath("/c/"))
  31. fmt.Println(simplifyPath("/a/./b/../../c/"))
  32. fmt.Println(simplifyPath("/../../"))
  33. }