Skip to content

Commit 17af691

Browse files
authored
feat: add swift implementation to lcof2 problem: No.117 (#3695)
1 parent 0843151 commit 17af691

File tree

2 files changed

+99
-0
lines changed

2 files changed

+99
-0
lines changed

lcof2/剑指 Offer II 117. 相似的字符串/README.md

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,58 @@ func numSimilarGroups(strs []string) int {
208208
}
209209
```
210210

211+
#### Swift
212+
213+
```swift
214+
class Solution {
215+
private var parent: [Int] = []
216+
217+
func numSimilarGroups(_ strs: [String]) -> Int {
218+
let n = strs.count
219+
parent = Array(0..<n)
220+
221+
for i in 0..<n {
222+
for j in (i + 1)..<n {
223+
if check(strs[i], strs[j]) {
224+
parent[find(i)] = find(j)
225+
}
226+
}
227+
}
228+
229+
var groups = 0
230+
for i in 0..<n {
231+
if i == find(i) {
232+
groups += 1
233+
}
234+
}
235+
return groups
236+
}
237+
238+
private func check(_ a: String, _ b: String) -> Bool {
239+
let n = a.count
240+
var count = 0
241+
let arrA = Array(a), arrB = Array(b)
242+
243+
for i in 0..<n {
244+
if arrA[i] != arrB[i] {
245+
count += 1
246+
}
247+
if count > 2 {
248+
return false
249+
}
250+
}
251+
return count <= 2
252+
}
253+
254+
private func find(_ x: Int) -> Int {
255+
if parent[x] != x {
256+
parent[x] = find(parent[x])
257+
}
258+
return parent[x]
259+
}
260+
}
261+
```
262+
211263
<!-- tabs:end -->
212264

213265
<!-- solution:end -->
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
class Solution {
2+
private var parent: [Int] = []
3+
4+
func numSimilarGroups(_ strs: [String]) -> Int {
5+
let n = strs.count
6+
parent = Array(0..<n)
7+
8+
for i in 0..<n {
9+
for j in (i + 1)..<n {
10+
if check(strs[i], strs[j]) {
11+
parent[find(i)] = find(j)
12+
}
13+
}
14+
}
15+
16+
var groups = 0
17+
for i in 0..<n {
18+
if i == find(i) {
19+
groups += 1
20+
}
21+
}
22+
return groups
23+
}
24+
25+
private func check(_ a: String, _ b: String) -> Bool {
26+
let n = a.count
27+
var count = 0
28+
let arrA = Array(a), arrB = Array(b)
29+
30+
for i in 0..<n {
31+
if arrA[i] != arrB[i] {
32+
count += 1
33+
}
34+
if count > 2 {
35+
return false
36+
}
37+
}
38+
return count <= 2
39+
}
40+
41+
private func find(_ x: Int) -> Int {
42+
if parent[x] != x {
43+
parent[x] = find(parent[x])
44+
}
45+
return parent[x]
46+
}
47+
}

0 commit comments

Comments
 (0)