ARTS挑战-第三周

什么是ARTS?

1.Algorithm:每周至少做一个 leetcode 的算法题
2.Review:阅读并点评至少一篇英文技术文章
3.Tip:学习至少一个技术技巧
4.Share:分享一篇有观点和思考的技术文章

Algorithm

这道题真是折磨人,一直被卡在 Time Limit Exceeded 。后来发现,我从一个字符串里取出char的时候的用法太耗时。
因为Swift不支持直接用下标取字符 error: 'subscript(_:)' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion,于是我就单独写了方法,通过 str[str.index(str.startIndex, offsetBy: index)] 获得字符,结果发现这玩意儿太耗时了。然而其实只需要将string强转为Array,就可以用下标取了。

Q:

Given a string, find the length of the longest substring without repeating characters.

Example 1:

1
2
3
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2:

1
2
3
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

1
2
3
4
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

A:

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
class Solution {

func lengthOfLongestSubstring(_ s: String) -> Int {
var l = 0
var r = -1
var ans = 0
var vis = [Character: Int]()
let chars = Array(s)

let size = chars.count

while l < size {
if r + 1 < size, (vis[chars[r + 1]] == nil || vis[chars[r + 1]] == 0) {
r += 1
vis[chars[r]] = 1
} else {
let lc = chars[l]

var x = -1
if let y = vis[lc] {
x = y - 1
}
vis[lc] = x
l += 1
}
ans = max(ans, r-l+1)
}
return ans
}
}

Review

Rethinking Design Patterns in Swift: State Pattern 这篇文章讲解了在Swift中状态模式的设计,非常清楚但是篇幅较长,需要耐心看完。

Tip

这周遇到一个很酷的方法,它将一个值与一个函数结合起来,并返回一个捕获该值的闭包,这样就可以在不需要任何参数的情况下调用它。在一些使用基于闭包的API中非常有用,因为这样我们就可以在不需要捕获self的情况下使用一些属性了。

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
func combine<A, B>(_ value: A, with closure: @escaping (A) -> B) -> () -> B {
return { closure(value) }
}

// BEFORE:

class ProductViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()

buyButton.handler = { [weak self] in
guard let self = self else {
return
}

self.productManager.startCheckout(for: self.product)
}
}
}

// AFTER:

class ProductViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()

buyButton.handler = combine(product, with: productManager.startCheckout)
}
}

Share

最近996.ICU异常火爆,很多程序员也在思考自己的编码生涯如何规划。恰巧看到这篇由《黑客与画家》的作者 保罗·格雷厄姆(Paul Graham)写的一篇博文 How to Make Wealth,感触良多,分享给大家。