题目地址
https://leetcode.com/problems/count-binary-substrings/
题目描述
696. Count Binary Substrings
Give a binary string s, return the number of non-empty 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.
Example 1:
Input: s = "00110011"
Output: 6
Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01".
Notice that some of these substrings repeat and are counted the number of times they occur.
Also, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together.
Example 2:
Input: s = "10101"
Output: 4
Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's.
思路
- 如果有3个连续的0接着4个连续的1. 则能组成的子串个数为3.
- 因此, 对于每次相邻的两个0与1, 能组成的子串个数为, 上一批的0的个数以及1的个数的最小值.
- for循环计算lastCount以及curCount.
关键点
- 注意, 由于是每次相邻的两个0与1, 我们统计上一组的0和1的个数, 因此, 在for循环结束后, 我们的res需要再进行一次比较累加操作.
代码
- 语言支持:Java
class Solution {
public int countBinarySubstrings(String s) {
int len = s.length();
int lastCount = 0;
int curCount = 1;
int res = 0;
char[] sc = s.toCharArray();
for (int i = 1; i < len; i++) {
if (sc[i] == sc[i - 1]) {
curCount++;
} else {
res += Math.min(lastCount, curCount);
lastCount = curCount;
curCount = 1;
}
}
res += Math.min(lastCount, curCount);
return res;
}
}
网友评论