/*
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("/.")
71. Simplify Path
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- Given an absolute path for a file (Unix-style), simplify ...
- 问题 Given an absolute path for a file (Unix-style), simpli...