Leetcode Note: Go - Count Binary Substrings

Count Binary Substrings - LeetCode
https://leetcode.com/problems/count-binary-substrings/

  • Go 言語で取り組んだメモ

所感

  • 2進数文字列 s に登場する部分文字列のパターンを int で return する
  • 例: s = 00110011 であれば下記の 6 パターンの部分文字列が存在する
    • 0011
    • 01
    • 1100
    • 10
    • 0011
    • 01
  • 例: s = 10101 であれば下記の 4 パターンの部分文字列が存在する
    • 10
    • 01
    • 10
    • 01

回答

Count Binary Substrings - LeetCode
https://leetcode.com/problems/count-binary-substrings/solution/

Python/Go O(n) by character grouping [w/ Hint] - LeetCode Discuss
https://leetcode.com/problems/count-binary-substrings/discuss/1172575/PythonGo-O(n)-by-character-grouping-w-Hint

func countBinarySubstrings(s string) int {

	// previous continuous occurrence, current continuous occurrence
	preContOcc, curContOcc := 0, 1

	// counter for binary substrings with equal 0s and 1s
	counter := 0

	// scan each character pair in s
	for idx := 1; idx < len(s); idx++ {

		if s[idx] == s[idx-1] {

			// update current continuous occurrence
			curContOcc += 1

		} else {

			// update counter of binary substring between previous character group and current character group
			counter += Min(preContOcc, curContOcc)

			// update previous as current's continuous occurrence
			preContOcc = curContOcc

			// reset current continuous occurrence to 1
			curContOcc = 1

		}

	}

	// update for last time
	counter += Min(preContOcc, curContOcc)

	return counter
}