思路:
首先分析题目要求的子串特点:0和1数量必须相等且不能交叉排列,即子串一半是0、另一半是1。
1、遍历原串s,统计连续相同字符的个数,存到list中;
2、遍历list,每相邻两个元素,取其中较小者(相等则任取其一)添加到sum中;
3、返回sum。
1 class Solution(object): 2 def countBinarySubstrings(self, s): 3 """ 4 :type s: str 5 :rtype: int 6 """ 7 # 计数器 8 num = 1 9 # 初始化list 10 listNum = [0] * len(s) 11 # i是list的有效下标 12 i = 0 13 # 返回值 14 sum = 0 15 16 # 遍历原串s,从下标1开始 17 for index in range(1, len(s)): 18 # 当前字符与前一个相等,计数器加1 19 if s[index] == s[index - 1]: 20 num += 1 21 # 当前字符与前一个不等,将上一个统计结果填到list中,list下标加1,重置计数器 22 else: 23 listNum[i] = num 24 # print(listNum) 25 i += 1 26 num = 1 27 # 填写最后一个统计结果 28 if index == len(s) - 1: 29 listNum[i] = num 30 i += 1 31 # print(listNum, i) 32 # 遍历list,取相邻元素较小者,计算结果 33 for j in range(1, i): 34 sum += min(listNum[j - 1], listNum[j]) 35 return sum 36 37 def countBinarySubstrings2(self, s): 38 """ 39 :type s: str 40 :rtype: int 41 """ 42 num1 = num0 = 0 43 ans = 0 44 for index, ch in enumerate(s): 45 if index == 0: 46 if ch == '0': 47 num0 += 1 48 else: 49 num1 += 1 50 else: 51 if ch == '0': 52 num0 = num0 + 1 if s[index - 1] == '0' else 1 53 if num1 >= num0: 54 ans += 1 55 elif ch == '1': 56 num1 = num1 + 1 if s[index - 1] == '1' else 1 57 if num0 >= num1: 58 ans += 1 59 return ans 60 61 62 if __name__ == '__main__': 63 solution = Solution() 64 print(solution.countBinarySubstrings("00110"))