Skip to content

Instantly share code, notes, and snippets.

@mmirolim
Last active May 8, 2018 15:33
Show Gist options
  • Save mmirolim/1ac8ab02e0cc40ab0b93202dc41d91af to your computer and use it in GitHub Desktop.
Save mmirolim/1ac8ab02e0cc40ab0b93202dc41d91af to your computer and use it in GitHub Desktop.
package reverse
func reverseStr(str string, specialChars string) string {
dic := map[byte]bool{}
for i := 0; i < len(specialChars); i++ {
dic[specialChars[i]] = true
}
// assume all are ascii characters
out := make([]byte, len(str))
l, r := 0, len(str)-1
for l <= r {
if dic[str[l]] {
out[l] = str[l]
l++
} else if dic[str[r]] {
out[r] = str[r]
r--
} else {
out[l], out[r] = str[r], str[l]
l++
r--
}
}
return string(out)
}
/*
package reverse
import (
"fmt"
"sort"
"testing"
)
func TestReverseArrayWithSpecialChars(t *testing.T) {
specialChars := ",!$"
cases := []struct {
in string
want string
}{
{in: "Ab,c,de!$", want: "ed,c,bA!$"},
{in: "a,b$c", want: "c,b$a"},
}
for i, tc := range cases {
out := reverseStr(tc.in, specialChars)
if tc.want != out {
t.Errorf("case %d, want %s, got %s", i, tc.want, out)
}
}
}
func TestSortOrder(t *testing.T) {
ints := []int{1, 10, 21, 2}
sort.Slice(ints, func(i, j int) bool {
return ints[i] > ints[j]
})
fmt.Printf("%+v\n", ints) // output for debug
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment