Python easy and concise solution (only 2 lines)


  • 14

    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!


Log in to reply
 

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