Skip to content

Commit c63df16

Browse files
committed
update description of 71_SimplifyPath
1 parent 845ee83 commit c63df16

File tree

3 files changed

+54
-3
lines changed

3 files changed

+54
-3
lines changed

71_SimplifyPath.swift

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
//
2+
// 71. 简化路径
3+
//
4+
// 题目链接:https://leetcode-cn.com/problems/simplify-path/
5+
// 标签:栈、字符串
6+
// 要点:根据题意,考虑清楚出入栈条件,以及跳过逻辑
7+
// 时间复杂度:O(N)
8+
// 空间复杂度:O(N)
9+
//
10+
11+
import Foundation
12+
13+
class Solution {
14+
func simplifyPath(_ path: String) -> String {
15+
let paths = path.split(separator: "/")
16+
17+
var pathStack = [String]()
18+
19+
for path in paths {
20+
guard path != ".", !path.isEmpty else { continue }
21+
22+
if path == ".." {
23+
pathStack.popLast()
24+
} else {
25+
pathStack.append(String(path))
26+
}
27+
}
28+
29+
return "/" + pathStack.joined(separator: "/")
30+
}
31+
}
32+
33+
// Tests
34+
let s = Solution()
35+
s.simplifyPath("/home/") == "/home"
36+
s.simplifyPath("/../") == "/"
37+
s.simplifyPath("/home//foo/") == "/home/foo"
38+
s.simplifyPath("/a/./b/../../c/") == "/c"
39+
s.simplifyPath("/a/../../b/../c//.//") == "/c"
40+
s.simplifyPath("/a//b////c/d//././/..") == "/a/b/c"

LeetCodePlayground.playground/Pages/71_SimplifyPath.xcplaygroundpage/Contents.swift

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,15 @@
11
//: [Previous](@previous)
22

3+
//
4+
// 71. 简化路径
5+
//
6+
// 题目链接:https://leetcode-cn.com/problems/simplify-path/
7+
// 标签:栈、字符串
8+
// 要点:根据题意,考虑清楚出入栈条件,以及跳过逻辑
9+
// 时间复杂度:O(N)
10+
// 空间复杂度:O(N)
11+
//
12+
313
import Foundation
414

515
class Solution {

README.md

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,10 @@ LeetCode 💖 Swift,攻克[数据结构](#数据结构)与[算法](#算法)。
5454

5555
###
5656

57-
| 标题 | 标签 | 描述 | 题解 |
58-
| :----------------------------------------------------------: | :-----------: | ------------------------------ | :--------------------------------------------------------: |
59-
| 1003. [检查替换后的词是否有效](https://leetcode-cn.com/problems/check-if-word-is-valid-after-substitutions/) | `字符串` `` | 按给定规则检查替换后的词有效性 | [Swift](./1003_CheckIfWordIsValidAfterSubstitutions.swift) |
57+
| 标题 | 标签 | 描述 | 题解 |
58+
| :----------------------------------------------------------: | :-----------: | ------------------------------------------------------------ | :--------------------------------------------------------: |
59+
| 1003. [检查替换后的词是否有效](https://leetcode-cn.com/problems/check-if-word-is-valid-after-substitutions/) | `字符串` `` | 按给定规则检查替换后的词有效性 | [Swift](./1003_CheckIfWordIsValidAfterSubstitutions.swift) |
60+
| [71. 简化路径](https://leetcode-cn.com/problems/simplify-path/) | `字符串` `` | 以 Unix 风格给出一个文件的**绝对路径**,你需要简化它。或者换句话说,将其转换为规范路径。 | [Swift](./71_SimplifyPath.swift) |
6061

6162
### 队列
6263

0 commit comments

Comments
 (0)