LeetCode 696 Count Binary Substrings 解题报告
题目要求
Give a string s, count the number of non-empty (contiguous) substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively.
Substrings that occur multiple times are counted the number of times they occur.
题目分析及思路
给定一个字符串,要求得到所有满足条件的非空连续子串的数目。子串需有相等数量的0和1,并且0和1都是各自连续的。若出现相同的子串则计算它们出现的次数。可以先确定原字符串中连续出现0或1的长度,存为数组groups。之后遍历groups,只要该数组元素保持不变或增大,则能确保原字符串中对应区间里的字符都能找到满足条件的子串;若变小,则只能取groups中较小元素的值m,说明此时只有m个字符能找到满足条件的子串。
python代码
class Solution:
def countBinarySubstrings(self, s: str) -> int:
groups = [1]
for i in range(1,len(s)):
if s[i-1] == s[i]:
groups[-1] += 1
else:
groups.append(1)
ans = 0
for i in range(1,len(groups)):
if groups[i-1] <= groups[i]:
ans += groups[i-1]
else:
ans += groups[i]
return ans
浙公网安备 33010602011771号