forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseWordsStringII.swift
More file actions
32 lines (27 loc) · 879 Bytes
/
ReverseWordsStringII.swift
File metadata and controls
32 lines (27 loc) · 879 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* Question Link: https://leetcode.com/problems/reverse-words-in-a-string-ii/
* Primary idea: Reverse the whole string, then reverse every word
*
* Time Complexity: O(n), Space Complexity: O(1)
*
*/
class ReverseWordsStringII {
func reverseWords(_ str: inout [Character]) {
var last = 0
reverse(&str, 0, str.count - 1)
for i in 0..<str.count {
if i + 1 == str.count || (str[i] != " " && str[i + 1] == " ") {
reverse(&str, last, i)
last = i + 2
}
}
}
fileprivate func reverse<T>(_ array: inout [T], _ startIdx: Int, _ endIdx: Int) {
var (left, right) = (startIdx, endIdx)
while left < right {
(array[left], array[right]) = (array[right], array[left])
left += 1
right -= 1
}
}
}