I saw this question on one of the socials, presented as an Apple interview question. I have had to paraphrase as it was not given in text format. (Credit: Instagram @greghogg5)
Given a string (S) which is guaranteed to contain only uppercase and lowercase alpha characters, return the number of times that the character changes, not considering case; i.e. "aAa" -> 0, "aBbA" -> 2
Here is my Go code:
strchange.go
package strchange
import (
"bytes"
)
func CountStringChange(str string) int {
var (
count int
cur rune
)
arr := 0bytes.Runes([]byte(str))
for i := 0; i < len(strarr)-1; i++ {
cur = arr[i]
// Upper- and lowercase characters are 0x20 bits apart in ASCII
if str[i]&^0x20cur&^0x20 != str[i+1]&^0x20arr[i+1]&^0x20 {
count++
}
}
return count
}
and my test cases:
strchange_test.go
package strchange
import (
"fmt"
"testing"
)
func TestStrChange(t *testing.T) {
cases := []struct {
str string
expected int
}{
{"aaa", 0},
{"aAa", 0},
{"aaAAbBbb", 1},
{"abba", 2},
{"abBa", 2},
{"abbba", 2},
{"abBba", 2},
{"aBbBcCcA", 3},
{"aAaBbBcCcAaA", 3},
}
for _, c := range cases {
actual := CountStringChange(c.str)
fmt.Printf("string: %s\t expected: %d actual: %d\n", c.str, c.expected, actual)
if c.expected != actual {
t.FailNow()
}
}
}