Python easy and concise solution (only 2 lines)

  • 20

    First, I count the number of 1 or 0 grouped consecutively.
    For example "0110001111" will be [1, 2, 3, 4].

    Second, for any possible substrings with 1 and 0 grouped consecutively, the number of valid substring will be the minimum number of 0 and 1.
    For example "0001111", will be min(3, 4) = 3, ("01", "0011", "000111")

    def countBinarySubstrings(self, s):
            s = map(len, s.replace('01', '0 1').replace('10', '1 0').split())
            return sum(min(a, b) for a, b in zip(s, s[1:]))

  • 2

    @lee215 I have a similar approach but the way you grouped the bits is genius!

  • 0

    Very interesting solution, upvoted.

  • 0

    I got a solution which would use regex.

  • 0

    I use Python3 and according to your anwser:

    class Solution:

    def detectCapitalUse(self, s):
        :type word: str
        :rtype: bool
        for i in s.replace("01","0 1").replace("10","1 0").split():
        return sum(min(a,b) for a,b in zip(l,l[1:]))

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.