-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathreverseWords.go
More file actions
32 lines (25 loc) · 864 Bytes
/
Copy pathreverseWords.go
File metadata and controls
32 lines (25 loc) · 864 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
/* https://leetcode.com/problems/reverse-words-in-a-string-iii/#/description
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
*/
package lstring
func reverseWords(s string) string {
sList := []byte(s)
reverse := func(sList []byte, start, end int) {
for i := 0; i < (end-start)/2; i++ {
sList[start+i], sList[end-1-i] = sList[end-1-i], sList[start+i]
}
}
start, end := 0, 0
for ; end < len(sList); end++ {
if sList[end] == ' ' {
reverse(sList, start, end)
start = end + 1
}
}
reverse(sList, start, end)
return string(sList)
}