forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimplifyPath.swift
36 lines (30 loc) · 989 Bytes
/
SimplifyPath.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* 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 res = ""
var stack = [String]()
let paths = path.characters.split {$0 == "/"}.map(String.init)
for path in paths {
var path = path.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
guard path != "." else {
continue
}
if path == ".." {
if (stack.count > 0) {
stack.removeLast()
}
} else if path.characters.count > 0 {
stack.append(path)
}
}
for str in stack {
res += "/"
res += str
}
return res.isEmpty ? "/" : res
}
}