Skip to content

Commit

Permalink
Added ch1p3 solution which is closer to the books solution after comm…
Browse files Browse the repository at this point in the history
…ents from paplorinc.
  • Loading branch information
lee-woodridge committed Feb 15, 2016
1 parent cf29314 commit 5666eba
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/chapter1/problem3.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,27 @@ func URLify(input string) string {
}
return string(temp)
}

// Less "real world" version taking a []rune with spaces
// on the end to be able to URLify in place.
// O(n), in place.
func URLifySlice(input []rune) {
inWord := false
slowPtr := len(input) - 1
for i := len(input) - 1; i >= 0; i-- {
if input[i] == rune(' ') {
if inWord {
input[slowPtr-2] = rune('%')
input[slowPtr-1] = rune('2')
input[slowPtr] = rune('0')
slowPtr -= 3
}
} else {
if !inWord {
inWord = true
}
input[slowPtr] = input[i]
slowPtr--
}
}
}
18 changes: 18 additions & 0 deletions src/chapter1/problem3_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package chapter1

import (
"reflect"
"testing"
)

Expand All @@ -21,3 +22,20 @@ func TestURLify(t *testing.T) {
}
}
}

func TestURLifySlice(t *testing.T) {
cases := []struct {
input []rune
expected []rune
}{
{[]rune("hello my name is "), []rune("hello%20my%20name%20is")},
{[]rune("hello"), []rune("hello")},
{[]rune(" hello my name is "), []rune("%20hello%20my%20name%20is")},
}
for _, c := range cases {
URLifySlice(c.input)
if !reflect.DeepEqual(c.expected, c.input) {
t.Fatalf("Expected: %s, actual: %s\n", string(c.expected), string(c.input))
}
}
}

0 comments on commit 5666eba

Please sign in to comment.