Python easy to understand solution with clear explanation


  • 0
    X

    When it changes, for example from 0 to 1, at the seperation line, count the most number of continuous 0's to the left and the most number of continuous 1's to the right, then take the minimum of the two. For example four 0's followed by three 1's will give us 3 candidate substrings. Then find all the seperation lines and sum up these minimum numbers. This will be the total number of qualified substrings
    '''

    def countBinarySubstrings(self, s):
       
        if s is None or len(s) <= 1:
            return 0
        
        count = 0
        n = len(s)
        count_curr = 0
        i = 0
        while i < n:
            count_prev = count_curr
            count_curr = 1
            i += 1
            
            while i < n and s[i] == s[i - 1]:
                count_curr += 1
                i += 1
            
            if i <= n:
                count += min(count_prev, count_curr) 
        
        return count
    

    '''


Log in to reply
 

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