TyranitarX Connect.

LeetCode每日打卡-2020-8-10

Word count: 501Reading time: 2 min
2020/08/10 Share

2020.8.10 每日题解 LeetCode 696. 计数二进制子串

PS:今天的题同样很简单 但是我写的很垃圾(
给定一个字符串 s,计算具有相同数量0和1的非空(连续)子字符串的数量,并且这些子字符串中的所有0和所有1都是组合在一起的。

重复出现的子串要计算它们出现的次数。

示例 1 :

1
2
3
4
5
6
7
输入: "00110011"
输出: 6
解释: 有6个子串具有相同数量的连续1和0:“0011”,“01”,“1100”,“10”,“0011” 和 “01”。

请注意,一些重复出现的子串要计算它们出现的次数。

另外,“00110011”不是有效的子串,因为所有的0(和1)没有组合在一起。

示例 2 :

1
2
3
4
输入: "10101"
输出: 4

解释: 有4个子串:“10”,“01”,“10”,“01”,它们具有相同数量的连续1和0。

注意:

s.length 在1到50,000之间。
s 只包含“0”或“1”字符。

思路详解

通过观察很简单能得到相邻最小重复组即为可得到的串数,即将字符串中重复0(1)组取出 记录最小值相加即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class E696_countBinarySubstrings {
public int countBinarySubstringsvegatable(String s) {
ArrayList<StringBuffer> list = new ArrayList<>();
int k = 0;
list.add(new StringBuffer(s.charAt(0) + ""));
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == '0' && s.charAt(i - 1) == '0') {
list.set(k, list.get(k).append("0"));
} else if (s.charAt(i) == '1' && s.charAt(i - 1) == '1') {
list.set(k, list.get(k).append("1"));
} else {
list.add(new StringBuffer(s.charAt(i) + ""));
k++;
}
}
int count = 0;
for (int i = 1; i < list.size(); i++) {
int num = Math.min(list.get(i).length(), list.get(i - 1).length());
count = count + num;
}
return count;
}

public int countBinarySubstringslessvegatable(String s) {
int[] lenths = new int[s.length()];
int k = 0;
lenths[0] = 1;
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == s.charAt(i - 1)) {
lenths[k]++;
} else {
k++;
lenths[k]++;
}
}
int count = 0;
for (int i = 1; i < lenths.length; i++) {
if (lenths[i] != 0) count = count + Math.min(lenths[i], lenths[i - 1]);
}
return count;
}
}
CATALOG
  1. 1. 2020.8.10 每日题解 LeetCode 696. 计数二进制子串
    1. 1.0.1. 思路详解