forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimplifyPath.swift
More file actions
23 lines (22 loc) · 783 Bytes
/
SimplifyPath.swift
File metadata and controls
23 lines (22 loc) · 783 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Question Link: https://leetcode.com/problems/simplify-path/
* Primary idea: Use a stack, normal to push, .. to pop
* Time Complexity: O(n), Space Complexity: O(n)
*/
class SimplifyPath {
func simplifyPath(_ path: String) -> String {
var directories = [String]()
let components = path.split(separator: "/")
for component in components {
switch component {
case "": break // do nothing
case ".": break // do nothing, pointing to the current directory
case "..":
directories.popLast() // if empty, does nothing
default:
directories.append(String(component))
}
}
return "/" + String(directories.joined(separator: "/"))
}
}