Leetcode 1869. Longer Contiguous Segments of Ones than Zeros
Given a binary string s, return true if the longest contiguous segment of ones is strictly longer than the longest contiguous segment of zeros in the string, or false otherwise.
s?Based on the problem statement, let’s implement the solution in C++.
#include <iostream>
#include <string>
using namespace std;
bool checkZeroOnes(string s) {
int maxOnes = 0, maxZeros = 0;
int currentOnes = 0, currentZeros = 0;
for (char c : s) {
if (c == '1') {
currentOnes++;
currentZeros = 0;
} else {
currentZeros++;
currentOnes = 0;
}
if (currentOnes > maxOnes) {
maxOnes = currentOnes;
}
if (currentZeros > maxZeros) {
maxZeros = currentZeros;
}
}
return maxOnes > maxZeros;
}
int main() {
// Test cases
cout << checkZeroOnes("1101") << endl; // Output: true
cout << checkZeroOnes("111000") << endl; // Output: false
cout << checkZeroOnes("110100010") << endl; // Output: false
return 0;
}
maxOnes and maxZeros to keep track of the maximum length of contiguous segments of ‘1’s and ‘0’s respectively.currentOnes and currentZeros to count the current segment lengths of ‘1’s and ‘0’s respectively.currentOnes and reset currentZeros to 0.currentZeros and reset currentOnes to 0.maxOnes and maxZeros whenever currentOnes or currentZeros exceed the recorded maximums.maxOnes and maxZeros to determine the result.The time complexity of this solution is O(n) where n is the length of the string:
The space complexity is O(1) because we are using a fixed amount of extra space for integer counters.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?