Fundamentals 6 min read

How to Find the Longest Consecutive 1s in a Binary String Using Java

This article explains several Java techniques—including a simple loop, String.split, and regular‑expression approaches—to compute the maximum number of consecutive '1' characters in a binary string, and even extends the method to handle mixed‑character inputs.

FunTester
FunTester
FunTester
How to Find the Longest Consecutive 1s in a Binary String Using Java

Problem Statement

Given a string consisting of characters '0' and '1', find the maximum number of consecutive '1's.

Iterative Loop Solution

Traverse the string once, maintaining max (the longest run found) and current (the length of the current run). When a '1' is encountered, increment current. When a '0' is encountered, compare current with max, update if larger, and reset current to zero. After the loop, perform a final comparison to handle a trailing run of '1's.

public class MaxConsecutiveOnes {
    public static void main(String[] args) {
        String str = "01011001011111101110101010110110";
        int max = 0;
        int current = 0;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c == '1') {
                current++;
            } else {
                if (current > max) {
                    max = current;
                }
                current = 0;
            }
        }
        // handle case where string ends with '1'
        if (current > max) {
            max = current;
        }
        System.out.println(max);
    }
}

Time complexity: O(n). Extra space: O(1).

Split‑Based Solution

Use String.split with the regular expression "0+" to break the input at one or more zeros. The resulting array contains only substrings of consecutive '1's. The longest element length is the answer.

public class MaxConsecutiveOnes {
    public static void main(String[] args) {
        String str = "01011001011111101110101010110110";
        String[] parts = str.split("0+");
        int max = 0;
        for (String part : parts) {
            if (part.length() > max) {
                max = part.length();
            }
        }
        System.out.println(max);
    }
}

Regex‑Match Solution

Use Pattern and Matcher to find all matches of the pattern "1+". Each match represents a run of '1's; the longest match length is the result.

import java.util.regex.*;

public class MaxConsecutiveOnes {
    public static void main(String[] args) {
        String str = "01011001011111101110101010110110";
        Pattern p = Pattern.compile("1+");
        Matcher m = p.matcher(str);
        int max = 0;
        while (m.find()) {
            int len = m.group().length();
            if (len > max) {
                max = len;
            }
        }
        System.out.println(max);
    }
}

Extended Version for Arbitrary Characters

If the input may contain characters other than '0' and '1', the same split approach can be applied by splitting on any character that is not '1'. The regex "((?!1).)+" matches maximal substrings of non‑'1' characters, leaving only the runs of '1's.

public class MaxConsecutiveOnes {
    public static void main(String[] args) {
        String str = "0dsa10fds1fdsa10010111111fd014341104310fdasfds10fsdafdsfdsa101101gfd10";
        String[] parts = str.split("((?!1).)+");
        int max = 0;
        for (String part : parts) {
            if (part.length() > max) {
                max = part.length();
            }
        }
        System.out.println(max);
    }
}

All three approaches produce the same result for a pure binary string; the last method generalizes to inputs containing other symbols.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaalgorithmCode Exampleregular expressionsiterationString processingsplit
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.