给出一个绝对路径,如:
1、/a/b/c/../ 输入/a/b
2、/a/b/./../ 输出/a
3、/a/b/c/../ 输入/a/b
注:
1、 ‘..’ 表示返回上个路径 ;
2、‘.’ 表示停留在当前路径;
override func viewDidLoad() {
super.viewDidLoad()
let str = simplifyPath("/a/b/../c/d/../../e/./a/./../c/../")
print(str)
}
func simplifyPath(_ path : String) -> String {
let paths = path.components(separatedBy: "/")
print(paths)
var stack = [String]()
for str in paths {
guard str != "" && str != "." else {
continue
}
if str == ".."{
//出栈
if stack.count > 0{
stack.popLast()
}
}else{
//进栈
stack.append(str)
}
}
return stack.reduce("") { (res, x) -> String in
return res + "/" + x
}
}
网友评论