Skip to content

Commit

Permalink
day 113: reverse sentence in place
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Dec 15, 2018
1 parent 234c0f1 commit 1bdcaef
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
30 changes: 28 additions & 2 deletions day113/problem.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package day113

import "strings"
import (
"strings"
)

// ReverseWords reverses the word position in the string.
// Runs in O(N) time and requires O(N) additional space.
Expand All @@ -15,5 +17,29 @@ func ReverseWords(str string) string {
// ReverseWordsInPlace reverses the word position in the string.
// Runs in O(N) time and requires O(1) additional space.
func ReverseWordsInPlace(str string) string {
return "here world hello"
r := []rune(str)
for i := 0; i < len(r)/2; i++ {
r[i], r[len(r)-1-i] = r[len(r)-1-i], r[i]
}
var start, end int
for end <= len(r) {
if end == len(r) {
reverseInPlace(r, start, end)
} else if r[end] == ' ' {
reverseInPlace(r, start, end)
start = end
for r[start] == ' ' {
start++
}
end = start - 1
}
end++
}
return string(r)
}

func reverseInPlace(r []rune, start, end int) {
for i := start; i < (start+end)/2; i++ {
r[i], r[end-1-(i-start)] = r[end-1-(i-start)], r[i]
}
}
1 change: 1 addition & 0 deletions day113/problem_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ var testcases = []struct {
input, expected string
}{
{"hello world here", "here world hello"},
{"greetings from colorado", "colorado from greetings"},
}

func TestReverseWords(t *testing.T) {
Expand Down

0 comments on commit 1bdcaef

Please sign in to comment.