2019独角兽企业重金招聘Python工程师标准>>>
问题:
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.
Example 1:
Input: "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: "10101" Output: 4 Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's.
Note:
s.length
will be between 1 and 50,000.s
will only consist of "0" or "1" characters.
解决:
【题意】给定一个01二进制字符串,看有多少个包含0和1数目相同的子字符串,而且要求是连续的0和1,也就是说像0101这样的不行,因为两个0不是连续的。
① 统计每个连续子串的个数,如,“1111000011010001011”转化为“4 4 2 1 1 3 1 1 2 ”,这样我们就可以方便的获得满足条件的子串个数,统计转化后的数组相邻元素之间最小的那个求和即可。
class Solution { //30ms
public int countBinarySubstrings(String s) {
int[] count = new int[s.length()];
int p = 0;
for (int i = 0;i < s.length() - 1;i ++){
count[p] ++;
if (s.charAt(i) != s.charAt(i + 1)){
p ++;
}
}
count[p] ++;//加上最后一个元素的处理
int res = 0;
for (int i = 0;i < p;i ++){
res += Math.min(count[i],count[i + 1]);
}
return res;
}
}
② 使用双指针,省去了记录的空间,只要使用两个变量记录即可。
class Solution { //23ms
public int countBinarySubstrings(String s) {
int len = s.length();
if (len <= 1) return 0;
char[] schar = s.toCharArray();
int i = 0;
int pre = -1;
int res = 0;
while(i < len){
int j = i;
char c = schar[i];
while(i < len && schar[i] == c) i ++;
int cur = i - j;
if (pre != -1) res += Math.min(pre,cur);
pre = cur;
}
return res;
}
}
③ 一样的遍历,只是一边遍历,一边记录结果。
class Solution { //23ms
public int countBinarySubstrings(String s) {
if (s == null || s.length() <= 1) return 0;
char[] schar = s.toCharArray();
int res = 0;
char prec = schar[0];
int count = 1;
int precount = 0;
for (int i = 1;i < schar.length;i ++){
if (prec == schar[i]){
count ++;
if (precount >= count){
res ++;
}
}else {
precount = count;
prec = schar[i];
count = 1;
res ++;
}
}
return res;
}
}