Skip to content

Commit 9d9a005

Browse files
committed
71. Simplify Path
1 parent f1d2144 commit 9d9a005

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ Not only Leetcode solutions in Swift.
77
* [16. 3Sum Closest](https://leetcode.com/problems/3sum-closest/)
88
* [18. 4Sum](https://leetcode.com/problems/4sum/)
99
* [46. Group Anagrams](https://leetcode.com/problems/anagrams/)
10+
* [71. Simplify Path](https://leetcode.com/problems/simplify-path/)
1011
* [134. Gas Station](https://leetcode.com/problems/gas-station/)
1112
* [167. Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/)
1213
* [170. Two Sum III - Data structure design](https://leetcode.com/problems/two-sum-iii-data-structure-design)

SwiftyLeetCode.playground/Contents.swift

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,55 @@ extension Solution {
227227
let groupAnagramsStrs = ["eat", "tea", "tan", "ate", "nat", "bat"]
228228
Solution.groupAnagrams(strs: groupAnagramsStrs)
229229

230+
/**
231+
* Question: 71. Simplify Path
232+
* Link: https://leetcode.com/problems/simplify-path/
233+
* Author: Peng
234+
*/
235+
236+
extension Solution {
237+
class func simplifyPath(path: String?) -> String? {
238+
guard let path = path, path.characters.count > 0 else {
239+
return nil
240+
}
241+
242+
var result = "/"
243+
let stubs = path.components(separatedBy: "/")
244+
var paths = [String]()
245+
246+
stubs.forEach { str in
247+
if (str == "..") {
248+
if (paths.count > 0) {
249+
paths.remove(at: paths.count - 1)
250+
}
251+
} else if (str != "." && str != "") {
252+
paths.append(str)
253+
}
254+
}
255+
256+
paths.forEach { path in
257+
result += path + "/"
258+
}
259+
260+
let resultLength = result.characters.count
261+
let index = result.index(result.startIndex, offsetBy: resultLength - 1)
262+
263+
if (resultLength > 1) {
264+
result = result.substring(to: index)
265+
}
266+
267+
return result
268+
}
269+
}
270+
271+
// usage
272+
273+
let path1 = "/home/"
274+
let path2 = "/a/./b/../../c/"
275+
276+
Solution.simplifyPath(path: path1)
277+
Solution.simplifyPath(path: path2)
278+
230279
/**
231280
* 134. Gas Station
232281
* https://leetcode.com/problems/gas-station/

0 commit comments

Comments
 (0)