Skip to content

Commit 59b9f53

Browse files
authored
feat: add swift implementation to lcof problem: No.58.1 (doocs#2948)
1 parent ac84901 commit 59b9f53

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

lcof/面试题58 - I. 翻转单词顺序/README.md

+30
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,36 @@ public class Solution {
251251
}
252252
```
253253

254+
#### Swift
255+
256+
```swift
257+
class Solution {
258+
func reverseWords(_ s: String) -> String {
259+
var words = [String]()
260+
var i = s.startIndex
261+
262+
while i < s.endIndex {
263+
while i < s.endIndex && s[i] == " " {
264+
i = s.index(after: i)
265+
}
266+
if i < s.endIndex {
267+
var t = ""
268+
var j = i
269+
while j < s.endIndex && s[j] != " " {
270+
t.append(s[j])
271+
j = s.index(after: j)
272+
}
273+
words.append(t)
274+
i = j
275+
}
276+
}
277+
278+
words.reverse()
279+
return words.joined(separator: " ")
280+
}
281+
}
282+
```
283+
254284
<!-- tabs:end -->
255285

256286
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution {
2+
func reverseWords(_ s: String) -> String {
3+
var words = [String]()
4+
var i = s.startIndex
5+
6+
while i < s.endIndex {
7+
while i < s.endIndex && s[i] == " " {
8+
i = s.index(after: i)
9+
}
10+
if i < s.endIndex {
11+
var t = ""
12+
var j = i
13+
while j < s.endIndex && s[j] != " " {
14+
t.append(s[j])
15+
j = s.index(after: j)
16+
}
17+
words.append(t)
18+
i = j
19+
}
20+
}
21+
22+
words.reverse()
23+
return words.joined(separator: " ")
24+
}
25+
}

0 commit comments

Comments
 (0)