LeetCode-in-Java

1869. Longer Contiguous Segments of Ones than Zeros

Easy

Given a binary string s, return true if the longest contiguous segment of 1s is strictly longer than the longest contiguous segment of 0s in s, or return false otherwise.

Note that if there are no 0’s, then the longest continuous segment of 0’s is considered to have a length 0. The same applies if there is no 1’s.

Example 1:

Input: s = “1101”

Output: true

Explanation:

The longest contiguous segment of 1s has length 2: “1101”

The longest contiguous segment of 0s has length 1: “1101”

The segment of 1s is longer, so return true.

Example 2:

Input: s = “111000”

Output: false

Explanation:

The longest contiguous segment of 1s has length 3: “111000”

The longest contiguous segment of 0s has length 3: “111000”

The segment of 1s is not longer, so return false.

Example 3:

Input: s = “110100010”

Output: false

Explanation:

The longest contiguous segment of 1s has length 2: “110100010”

The longest contiguous segment of 0s has length 3: “110100010”

The segment of 1s is not longer, so return false.

Constraints:

Solution

public class Solution {
    public boolean checkZeroOnes(String s) {
        int zeroes = 0;
        int ones = 0;
        int i = 0;
        while (i < s.length()) {
            int start = i;
            while (i < s.length() && s.charAt(i) == '0') {
                i++;
            }
            if (i > start) {
                zeroes = Math.max(zeroes, i - start);
            }
            start = i;
            while (i < s.length() && s.charAt(i) == '1') {
                i++;
            }
            if (i > start) {
                ones = Math.max(ones, i - start);
            }
        }
        return ones > zeroes;
    }
}