Skip to content

Commit e566918

Browse files
authored
feat: add swift implementation to lcof2 problem: No.063 (#3132)
1 parent 2c4e4fc commit e566918

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

lcof2/剑指 Offer II 063. 替换单词/README.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,30 @@ func replaceWords(dictionary []string, sentence string) string {
172172
}
173173
```
174174

175+
#### Swift
176+
177+
```swift
178+
class Solution {
179+
func replaceWords(_ dictionary: [String], _ sentence: String) -> String {
180+
let dictSet = Set(dictionary)
181+
var words = sentence.split(separator: " ").map { String($0) }
182+
183+
for i in 0..<words.count {
184+
let word = words[i]
185+
for j in 1...word.count {
186+
let prefix = String(word.prefix(j))
187+
if dictSet.contains(prefix) {
188+
words[i] = prefix
189+
break
190+
}
191+
}
192+
}
193+
194+
return words.joined(separator: " ")
195+
}
196+
}
197+
```
198+
175199
<!-- tabs:end -->
176200

177201
<!-- solution:end -->
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
func replaceWords(_ dictionary: [String], _ sentence: String) -> String {
3+
let dictSet = Set(dictionary)
4+
var words = sentence.split(separator: " ").map { String($0) }
5+
6+
for i in 0..<words.count {
7+
let word = words[i]
8+
for j in 1...word.count {
9+
let prefix = String(word.prefix(j))
10+
if dictSet.contains(prefix) {
11+
words[i] = prefix
12+
break
13+
}
14+
}
15+
}
16+
17+
return words.joined(separator: " ")
18+
}
19+
}

0 commit comments

Comments
 (0)