696.计数二进制子串

79 阅读1分钟

题目:
给定一个字符串 s,统计并返回具有相同数量 0 和 1 的非空(连续)子字符串的数量,并且这些子字符串中的所有 0 和所有 1 都是成组连续的。

重复出现(不同位置)的子串也要统计它们出现的次数。
解法:
reverseAppered出现之后才能进行count增加计算,防止00110011在j=6开始的时候误算了 方法一:

func countBinarySubstrings(s string) int {
	count := 0
	
	for i := 0; i < len(s); {
		subStrCount := 1

		j := i + 1
		reverseAppered := false
		reverseAppereIndex := j
		for ; j < len(s) && subStrCount != 0 ; j ++ {
			if s[i] == s[j]  {
				if reverseAppered {
					break
				} 
				subStrCount ++
			} else {
				if !reverseAppered {
					reverseAppered = true
					reverseAppereIndex = j
				}
				subStrCount --
				
			}
		}
		if reverseAppered {
			count = count + j - reverseAppereIndex
		}
			
		i = reverseAppereIndex
		
	}
	return count
}

方法二:区间思想

func countBinarySubstrings(s string) int {
	// cur表示最近一个连续的0或者1的个数。
	cur, pre := 1, 0
	count := 0
	for j := 1; j < len(s); j ++ {
		if s[j] == s[j - 1] {
			cur ++
		} else {
			pre = cur
			cur = 1
		}
		if pre >= cur {
			count ++
		}
	}
	
	return count
}