Skip to content

696. Count Binary Substrings 👍

  • 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
class Solution {
 public:
  int countBinarySubstrings(string s) {
    int ans = 0;
    int prevEquals = 0;
    int currEquals = 1;

    for (int i = 0; i + 1 < s.length(); ++i)
      if (s[i] == s[i + 1])
        ++currEquals;
      else {
        ans += min(prevEquals, currEquals);
        prevEquals = currEquals;
        currEquals = 1;
      }

    return ans + min(prevEquals, currEquals);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int countBinarySubstrings(String s) {
    int ans = 0;
    int prevEquals = 0;
    int currEquals = 1;

    for (int i = 0; i + 1 < s.length(); ++i)
      if (s.charAt(i) == s.charAt(i + 1))
        ++currEquals;
      else {
        ans += Math.min(prevEquals, currEquals);
        prevEquals = currEquals;
        currEquals = 1;
      }

    return ans + Math.min(prevEquals, currEquals);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def countBinarySubstrings(self, s: str) -> int:
    ans = 0
    prevCount = 0
    equals = 1

    for i in range(len(s) - 1):
      if s[i] == s[i + 1]:
        equals += 1
      else:
        ans += min(prevCount, equals)
        prevCount = equals
        equals = 1

    return ans + min(prevCount, equals)