Skip to content

Commit c79c5e2

Browse files
authored
feat: add swift implementation to lcof problem: No.19 (doocs#2878)
1 parent d470682 commit c79c5e2

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

lcof/面试题19. 正则表达式匹配/README.md

+38
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,44 @@ public class Solution {
281281
}
282282
```
283283

284+
#### Swift
285+
286+
```swift
287+
class Solution {
288+
private var memo: [[Bool?]] = []
289+
private var s: [Character] = []
290+
private var p: [Character] = []
291+
private var m: Int = 0
292+
private var n: Int = 0
293+
294+
func isMatch(_ s: String, _ p: String) -> Bool {
295+
self.s = Array(s)
296+
self.p = Array(p)
297+
self.m = s.count
298+
self.n = p.count
299+
self.memo = Array(repeating: Array(repeating: nil, count: n + 1), count: m + 1)
300+
return dfs(0, 0)
301+
}
302+
303+
private func dfs(_ i: Int, _ j: Int) -> Bool {
304+
if j >= n {
305+
return i == m
306+
}
307+
if let res = memo[i][j] {
308+
return res
309+
}
310+
var res = false
311+
if j + 1 < n && p[j + 1] == "*" {
312+
res = dfs(i, j + 2) || (i < m && (s[i] == p[j] || p[j] == ".") && dfs(i + 1, j))
313+
} else {
314+
res = i < m && (s[i] == p[j] || p[j] == ".") && dfs(i + 1, j + 1)
315+
}
316+
memo[i][j] = res
317+
return res
318+
}
319+
}
320+
```
321+
284322
<!-- tabs:end -->
285323

286324
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
private var memo: [[Bool?]] = []
3+
private var s: [Character] = []
4+
private var p: [Character] = []
5+
private var m: Int = 0
6+
private var n: Int = 0
7+
8+
func isMatch(_ s: String, _ p: String) -> Bool {
9+
self.s = Array(s)
10+
self.p = Array(p)
11+
self.m = s.count
12+
self.n = p.count
13+
self.memo = Array(repeating: Array(repeating: nil, count: n + 1), count: m + 1)
14+
return dfs(0, 0)
15+
}
16+
17+
private func dfs(_ i: Int, _ j: Int) -> Bool {
18+
if j >= n {
19+
return i == m
20+
}
21+
if let res = memo[i][j] {
22+
return res
23+
}
24+
var res = false
25+
if j + 1 < n && p[j + 1] == "*" {
26+
res = dfs(i, j + 2) || (i < m && (s[i] == p[j] || p[j] == ".") && dfs(i + 1, j))
27+
} else {
28+
res = i < m && (s[i] == p[j] || p[j] == ".") && dfs(i + 1, j + 1)
29+
}
30+
memo[i][j] = res
31+
return res
32+
}
33+
}

0 commit comments

Comments
 (0)