LeetCode 1869: Longer Contiguous Segments of Ones than Zeros Solution
Master LeetCode problem 1869 (Longer Contiguous Segments of Ones than Zeros), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1869. Longer Contiguous Segments of Ones than Zeros
Problem Explanation
Explanation:
To solve this problem, we can iterate through the binary string s and keep track of the lengths of the current contiguous segments of ones and zeros. We update the maximum lengths for ones and zeros whenever we encounter a different digit or reach the end of the string. Finally, we compare the maximum lengths for ones and zeros and return true if the length of the ones segment is strictly greater than the length of the zeros segment.
- Initialize variables
maxOnesandmaxZerosto store the maximum lengths of contiguous ones and zeros, respectively. - Initialize variables
currentOnesandcurrentZerosto store the current lengths of contiguous ones and zeros, respectively. - Iterate through the string
s:- If the current character is a '1', increment
currentOnesand resetcurrentZerosto 0. - If the current character is a '0', increment
currentZerosand resetcurrentOnesto 0. - Update
maxOnesandmaxZeroswith the maximum of their current values and the current lengths.
- If the current character is a '1', increment
- Check if
maxOnesis strictly greater thanmaxZerosand return the result.
Time Complexity: O(n) where n is the length of the input string s. Space Complexity: O(1)
Solution Code
class Solution {
public boolean checkZeroOnes(String s) {
int maxOnes = 0, maxZeros = 0;
int currentOnes = 0, currentZeros = 0;
for (char c : s.toCharArray()) {
if (c == '1') {
currentOnes++;
currentZeros = 0;
} else {
currentZeros++;
currentOnes = 0;
}
maxOnes = Math.max(maxOnes, currentOnes);
maxZeros = Math.max(maxZeros, currentZeros);
}
return maxOnes > maxZeros;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1869 (Longer Contiguous Segments of Ones than Zeros)?
This page provides optimized solutions for LeetCode problem 1869 (Longer Contiguous Segments of Ones than Zeros) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1869 (Longer Contiguous Segments of Ones than Zeros)?
The time complexity for LeetCode 1869 (Longer Contiguous Segments of Ones than Zeros) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1869 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1869 in Java, C++, or Python.