diff --git a/src/chapter1/problem3.go b/src/chapter1/problem3.go index 0e1cc5a..cb64116 100644 --- a/src/chapter1/problem3.go +++ b/src/chapter1/problem3.go @@ -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-- + } + } +} diff --git a/src/chapter1/problem3_test.go b/src/chapter1/problem3_test.go index 8256550..5ae2ff4 100644 --- a/src/chapter1/problem3_test.go +++ b/src/chapter1/problem3_test.go @@ -1,6 +1,7 @@ package chapter1 import ( + "reflect" "testing" ) @@ -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)) + } + } +}