LeetCode: Count Binary Substrings Solution

1/*
2 group and count contiguous 0s/1s
3 "00110011"
4 => [2, 2, 2, 2]
5
6 sum of the minimum adjacent pairs
7 [2, 2, 2, 2]
8 => 2 + 2 + 2 = 6
9*/
10
11/**
12 * @param {string} s
13 * @return {number}
14 */
15var countBinarySubstrings = function (s) {
16 // group and count contiguous 0s/1s
17 const groups = [1]
18 for (let i = 1; i < s.length; i++) {
19 if (s[i] === s[i - 1]) {
20 groups[groups.length - 1]++
21 } else {
22 groups.push(1)
23 }
24 }
25
26 // sum of the minimum adjacent
27 let res = 0
28 for (let i = 0; i < groups.length - 1; i++) {
29 res += Math.min(groups[i], groups[i + 1])
30 }
31
32 return res
33}

Comments

Loading comments...

Tags

leetcode

string

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Power Of Three

Apr 27, 2021

Previous Post

HoningJS

Search Posts