Skip to content

Commit

Permalink
Merge 47b47d6 into e1d2575
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Dec 15, 2018
2 parents e1d2575 + 47b47d6 commit 5d51bda
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,3 +121,4 @@ problems from
* [Day 109](https://github.com/vaskoz/dailycodingproblem-go/issues/229)
* [Day 110](https://github.com/vaskoz/dailycodingproblem-go/issues/231)
* [Day 111](https://github.com/vaskoz/dailycodingproblem-go/issues/232)
* [Day 114](https://github.com/vaskoz/dailycodingproblem-go/issues/237)
38 changes: 38 additions & 0 deletions day114/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package day114

import "strings"

// ReverseWordsMaintainDelimters reverses the words in the string
// while maintaining the relative order of the delimiters
// Works only with two delimiters "/" or ":"
// Runs in O(N) time and requires O(N) extra space to construct the result.
func ReverseWordsMaintainDelimters(str string) string {
var start, end int
var words []string
var delimiters []string
for end <= len(str) {
if end == len(str) {
if str[end-1] != ':' && str[end-1] != '/' {
words = append(words, str[start:end])
}
break
}
if str[end] == '/' || str[end] == ':' {
delimiters = append(delimiters, string(str[end]))
words = append(words, str[start:end])
start = end + 1
}
end++
}
for i := 0; i < len(words)/2; i++ {
words[i], words[len(words)-1-i] = words[len(words)-1-i], words[i]
}
var result []string
if len(delimiters) != len(words) {
delimiters = append([]string{""}, delimiters...)
}
for i := range words {
result = append(result, delimiters[i], words[i])
}
return strings.Join(result, "")
}
29 changes: 29 additions & 0 deletions day114/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package day114

import "testing"

var testcases = []struct {
input, expected string
}{
{"hello/world:here", "here/world:hello"},
{"hello/world:here/", "/here:world/hello"},
{"hello//world:here", "here/world/:hello"},
{"/hello//world:here/", "/here/world/:hello/"},
}

func TestReverseWordsMaintainDelimters(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := ReverseWordsMaintainDelimters(tc.input); result != tc.expected {
t.Errorf("Expected %v got %v", tc.expected, result)
}
}
}

func BenchmarkReverseWordsMaintainDelimters(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
ReverseWordsMaintainDelimters(tc.input)
}
}
}

0 comments on commit 5d51bda

Please sign in to comment.