题目来源:https://leetcode.com/problems/simplify-path/
问题描述
71. Simplify Path
Medium
Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.
In a UNIX-style file system, a period .
refers to the current directory. Furthermore, a double period ..
moves the directory up a level. For more information, see: Absolute path vs relative path in Linux/Unix
Note that the returned canonical path must always begin with a slash /
, and there must be only a single slash /
between two directory names. The last directory name (if it exists) must not end with a trailing /
. Also, the canonical path must be the shortest string representing the absolute path.
Example 1:
Input: "/home/"
Output: "/home"
Explanation: Note that there is no trailing slash after the last directory name.
Example 2:
Input: "/../"
Output: "/"
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
Example 3:
Input: "/home//foo/"
Output: "/home/foo"
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
Example 4:
Input: "/a/./b/../../c/"
Output: "/c"
Example 5:
Input: "/a/../../b/../c//.//"
Output: "/c"
Example 6:
Input: "/a//bc/d//././/.."
Output: "/a/b/c"
------------------------------------------------------------
题意
化简Unix风格的绝对路径
------------------------------------------------------------
思路
用栈,遇到”..”则栈顶出栈,遇到”.”则不操作,遇到其他字符串则入栈。注意edge case也就是根目录的处理:当输入为空字符串时,表示根目录,要输出”/”
(吐槽一下Golang的设计,为了简化语言居然连泛型都没有,也没有class,是用struct和method实现的面向对象,这两点在封装数据结构的时候感觉很不方便)
------------------------------------------------------------
代码
func simplifyPath(path string) string {
n := len(path)
l := list.New()
last_slash := 0
for i := 1; i<n; i++ {
if path[i] == '/' {
if i - last_slash > 1 {
if path[last_slash+1:i] == ".." {
if l.Len() > 0 {
l.Remove(l.Back())
}
} else if path[last_slash+1:i] == "." {
} else {
l.PushBack(path[last_slash+1:i])
}
}
last_slash = i
}
}
if last_slash < n-1 {
if path[last_slash+1:n] == ".." {
if l.Len() > 0 {
l.Remove(l.Back())
}
} else if path[last_slash+1:n] == "." {
} else {
l.PushBack(path[last_slash+1:n])
}
}
if l.Len() == 0 {
return "/"
}
var buffer bytes.Buffer
for e:=l.Front(); e!=nil; e=e.Next() {
buffer.WriteString("/")
buffer.WriteString(e.Value.(string))
}
return buffer.String()
}