Count Sub Strings in Binary Array With equal Consecutive 0 and 1

package org.wesome.dsalgo;

public class CountBinarySubstring {
    static int countBinarySubstring(String binaryStr) {
        final char Zero = '0';
        final char One = '1';
        int count = 0, zeroIndx = 0, oneIndx = 0, length = binaryStr.length();
        while (zeroIndx < length) {
            int zeroCount = 0, oneCount = 0;
            /*  if current element is 0 */
            if (binaryStr.charAt(zeroIndx) == Zero) {
                /*  while element is 0, count and increment zeroCount  */
                while (zeroIndx < length && binaryStr.charAt(zeroIndx) == Zero) {
                    zeroCount++;
                    zeroIndx++;
                }
                /*  if 1 started after 0, then count 1 and increase the oneCount    */
                oneIndx = zeroIndx;
                while (oneIndx < length && binaryStr.charAt(oneIndx) == One) {
                    oneCount++;
                    oneIndx++;
                }
            } else {
                /*  if current element is 1 */
                /*  while element is 1, count and increment oneCount  */
                while (zeroIndx < length && binaryStr.charAt(zeroIndx) == One) {
                    oneCount++;
                    zeroIndx++;
                }
                /*  if 0 started after 1, then count 0 and increase the zeroCount    */
                oneIndx = zeroIndx;
                while (oneIndx < length && binaryStr.charAt(oneIndx) == Zero) {
                    zeroCount++;
                    oneIndx++;
                }
            }
            count += Math.min(zeroCount, oneCount);
        }
        return count;
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import static org.wesome.dsalgo.CountBinarySubstring.countBinarySubstring;

public class CountBinarySubstringTest {
    @Test
    void countBinarySubstringTest1() {
        String binaryString = "0001110010";
        Assertions.assertEquals(7, countBinarySubstring(binaryString));
    }

    @Test
    void countBinarySubstringTest2() {
        String binaryString = "110010";
        Assertions.assertEquals(4, countBinarySubstring(binaryString));
    }
}
plugins {
    id 'java'
    id "io.freefair.lombok" version "6.2.0"
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}

test {
    useJUnitPlatform()
}

 

follow us on