目录结构
1.题目
给定一个字符串 s,计算具有相同数量0和1的非空(连续)子字符串的数量,并且这些子字符串中的所有0和所有1都是组合在一起的。
重复出现的子串要计算它们出现的次数。
示例:
输入: "00110011"
输出: 6
解释: 有6个子串具有相同数量的连续1和0:“0011”,“01”,“1100”,“10”,“0011” 和 “01”。
请注意,一些重复出现的子串要计算它们出现的次数。
另外,“00110011”不是有效的子串,因为所有的0(和1)没有组合在一起。
输入: "10101"
输出: 4
解释: 有4个子串:“10”,“01”,“10”,“01”,它们具有相同数量的连续1和0。
注意:
s.length
在1到50,000之间。s
只包含“0”或“1”字符。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-binary-substrings
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
2.1相同字符连续块分组
将字符串 s 按相同字符连续块分组,即记录每个相同字符连续块的长度。
则'0' * k + '1' * k
或 '1' * k + '0' * k
形式的每个二进制字符串的数量由相邻两个相同字符连续块的最小长度决定。
public class Solution696 {
@Test
public void test696() {
System.out.println(countBinarySubstrings("00110011"));
}
public int countBinarySubstrings(String s) {
int[] count = new int[s.length()];
int p = 0, result = 0;
count[0] = 1;
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i - 1) != s.charAt(i)) {
count[++p] = 1;
} else {
count[p]++;
}
}
for (int i = 0; i < p; i++) {
result += Math.min(count[i], count[i + 1]);
}
return result;
}
}
- 时间复杂度:
- 空间复杂度:
2.2相同字符连续块分组+空间优化
由2.1看出,实际上只需保留相邻两个块的计数值,而不用保存所有。
public class Solution696 {
@Test
public void test696() {
System.out.println(countBinarySubstrings("00110011"));
}
public int countBinarySubstrings(String s) {
int preCount = 0, currCount = 1, result = 0;
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i - 1) != s.charAt(i)) {
result += Math.min(preCount, currCount);
preCount = currCount;
currCount = 1;
} else {
currCount++;
}
}
return result + Math.min(preCount, currCount);
}
}
- 时间复杂度:
- 空间复杂度: