Skip to content

1869. Longer Contiguous Segments of Ones than Zeros 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  bool checkZeroOnes(string s) {
    int longestOnes = 0;
    int longestZeros = 0;
    int currentOnes = 0;
    int currentZeros = 0;

    for (const char c : s)
      if (c == '0') {
        currentOnes = 0;
        longestZeros = max(longestZeros, ++currentZeros);
      } else {
        currentZeros = 0;
        longestOnes = max(longestOnes, ++currentOnes);
      }

    return longestOnes > longestZeros;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public boolean checkZeroOnes(String s) {
    int longestOnes = 0;
    int longestZeros = 0;
    int currentOnes = 0;
    int currentZeros = 0;

    for (final char c : s.toCharArray())
      if (c == '0') {
        currentOnes = 0;
        longestZeros = Math.max(longestZeros, ++currentZeros);
      } else {
        currentZeros = 0;
        longestOnes = Math.max(longestOnes, ++currentOnes);
      }

    return longestOnes > longestZeros;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
  def checkZeroOnes(self, s: str) -> bool:
    longestOnes = 0
    longestZeros = 0
    currentOnes = 0
    currentZeros = 0

    for c in s:
      if c == '0':
        currentOnes = 0
        currentZeros += 1
        longestZeros = max(longestZeros, currentZeros)
      else:
        currentZeros = 0
        currentOnes += 1
        longestOnes = max(longestOnes, currentOnes)

    return longestOnes > longestZeros