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 := bytes.Runes([]byte(str)) for i := 0; i < len(arr)-1; i++ { cur = arr[i] // Upper- and lowercase characters are 0x20 bits apart in ASCII if cur&^0x20 != arr[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() } } }
str
consists of only upper case and lower case English letters.\$\endgroup\$cur&^0x20
works fine in ascii, but you're explicitly usingrune
. That makes no sense. Arune
is a UTF-8 character,byte
is ASCII. Are you using multi-byte characters? If so,strings.ToLower
exists, why make things harder? If performance is important, you may want to skip theToLower
call, but otherwise, I wouldn't worry about it too much, eliminate the variable of upper/lower case by normalising the input\$\endgroup\$str
consists of only upper case and lower case English letters.". If you don't answer the question then you get an F and we won't hire you.\$\endgroup\$