/*
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
Corner Cases:
Did you consider the case where path = "/../"?
In this case, you should return "/".
Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
In this case, you should ignore redundant slashes and return "/home/foo".
*/
/*
Thinking:
1. 遇到 .. 丢弃前面一项,. 直接跳过, ...则要保留。
2. 遇到双 // 则要变为到 / 。
3. 尾部的 / 要丢弃。
考虑字符串分割的特性,// 会被 / 分割,则空的子串会被丢弃
所以先把字符串分割为数组,然后过滤空内容,遇到 .. 则把前面的丢弃。
*/
import Foundation
class Solution {
func simplifyPath(_ path: String) -> String {
guard path.lengthOfBytes(using: .ascii) > 0 else {
return ""
}
guard path != "/" else {
return "/"
}
let pathArray = path.components(separatedBy: "/")
let unEmptyArray = pathArray.filter() {
!($0 as String).isEmpty
}
var retArray: [String] = []
for value in unEmptyArray {
if value == ".." {
//如果包含 . 则情况之前的
if !retArray.isEmpty {
retArray.removeLast()
}
} else if value != "." {
retArray.append(value)
}
}
var retStr = "/"
for value in retArray {
retStr.append(value)
if retArray.last != value {
//非最后一个的情况下, 合并 "/"
retStr.append("/")
}
}
print(retStr)
return retStr
}
}
let solution = Solution()
solution.simplifyPath("/.")
网友评论