LeetCode-696-计数二进制子串
2020-10-28 本文已影响0人
阿凯被注册了
给定一个字符串 s,计算具有相同数量0和1的非空(连续)子字符串的数量,并且这些子字符串中的所有0和所有1都是组合在一起的。
重复出现的子串要计算它们出现的次数。
image.png
解题思路:
- 中心扩展,偶数位的回文子串,从
i-1,i
分布向两边扩展遍历,保证s[i-1]!=s[i]
,且保持一致,result
累计。
Python3代码:
class Solution:
def countBinarySubstrings(self, s: str) -> int:
# 中心扩展
result = 0
for i in range(len(s)):
left, right = i-1, i
left_char = s[left]
right_char = s[right]
if left_char==right_char:
continue
else:
while left>=0 and right<len(s) and s[left]==left_char and s[right]==right_char:
left-=1
right+=1
result+=1
return result