Skip to content

Commit ebefc76

Browse files
authoredMay 27, 2024
feat: add swift implementation to lcof problem: No.38 (doocs#2919)
1 parent 63da6ef commit ebefc76

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed
 

‎lcof/面试题38. 字符串的排列/README.md

+37
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,43 @@ public class Solution {
283283
}
284284
```
285285

286+
#### Swift
287+
288+
```swift
289+
class Solution {
290+
private var ans: [String] = []
291+
private var cs: [Character] = []
292+
293+
func permutation(_ s: String) -> [String] {
294+
cs = Array(s)
295+
dfs(0)
296+
return ans
297+
}
298+
299+
private func dfs(_ i: Int) {
300+
if i == cs.count - 1 {
301+
ans.append(String(cs))
302+
return
303+
}
304+
var vis: Set<Character> = []
305+
for j in i..<cs.count {
306+
if !vis.contains(cs[j]) {
307+
vis.insert(cs[j])
308+
swap(i, j)
309+
dfs(i + 1)
310+
swap(i, j)
311+
}
312+
}
313+
}
314+
315+
private func swap(_ i: Int, _ j: Int) {
316+
let t = cs[i]
317+
cs[i] = cs[j]
318+
cs[j] = t
319+
}
320+
}
321+
```
322+
286323
<!-- tabs:end -->
287324

288325
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
private var ans: [String] = []
3+
private var cs: [Character] = []
4+
5+
func permutation(_ s: String) -> [String] {
6+
cs = Array(s)
7+
dfs(0)
8+
return ans
9+
}
10+
11+
private func dfs(_ i: Int) {
12+
if i == cs.count - 1 {
13+
ans.append(String(cs))
14+
return
15+
}
16+
var vis: Set<Character> = []
17+
for j in i..<cs.count {
18+
if !vis.contains(cs[j]) {
19+
vis.insert(cs[j])
20+
swap(i, j)
21+
dfs(i + 1)
22+
swap(i, j)
23+
}
24+
}
25+
}
26+
27+
private func swap(_ i: Int, _ j: Int) {
28+
let t = cs[i]
29+
cs[i] = cs[j]
30+
cs[j] = t
31+
}
32+
}

0 commit comments

Comments
 (0)
Please sign in to comment.