/*
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. 遇到雙 // 則要變?yōu)榈?/ 。
3. 尾部的 / 要丟棄。
考慮字符串分割的特性,// 會被 / 分割,則空的子串會被丟棄
所以先把字符串分割為數(shù)組,然后過濾空內(nèi)容,遇到 .. 則把前面的丟棄。
*/
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
最后編輯于 :
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
推薦閱讀更多精彩內(nèi)容
- Given an absolute path for a file (Unix-style), simplify ...
- 問題 Given an absolute path for a file (Unix-style), simpli...