您的位置:首页 > 其它

696. Count Binary Substrings

2017-10-19 14:53 113 查看
问题: 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.

问题描述:找到所有子串,其中0和1的数量相同,且0和1分别连续。

解题思路:计算连续0或者1的数量number1,接着数值变化了以后,先记录此时的位置position,同时计算连续1或者0的数量number2,此时子串的数量为number1和number2的较小值。从记录的位置position开始。

class Solution {
public int countBinarySubstrings(String s) {
int count = 0;
int total = 1;//解题思路中的number1
int sum = 0;//解题思路中的number2
int begin = 0;//用来记录开始的位置
char[] sArray = s.toCharArray();
if(sArray.length == 1) return 0;
int judge = sArray[0];
for(int i = 1; i < sArray.length; ++i){
if( sArray[i] == judge)  ++total;
if( sArray[i] != judge && sArray[i-1] == judge ){
begin = i;
for(;i < sArray.length && sArray[i] !=judge; ++i){
count ++;
}
sum += Math.min(total,count);
total = 1;
count = 0;
i = begin;
judge = sArray[i];
}

}
return sum;
}
}


改进: 假设num1个连续出现的0与num2个连续出现的1相邻,则这个字符串的中子串的数量就是num1与num2的较小值。比如00111的子串大小就是2和3中的较小值。之前的解法重复计算了连续0或1的个数。改进代码如下:

class Solution {
public int countBinarySubstrings(String s) {
int num1 = 1;
int num2 = 0;
int sum = 0;
int i = 1;
char[] sArray = s.toCharArray();
if(sArray.length == 1) return 0;
char judge = sArray[0];
for(  ; i < sArray.length && sArray[i] == judge ; ++i){
++ num1;
}
for( ; i < sArray.length ; ++ i ){
if(sArray[i] != judge) num2++;
if(sArray[i] == judge && sArray[i-1] != judge){
sum += Math.min(num1 , num2);
num1 = num2;
num2 = 1;
judge = sArray[i-1];
}
if(i == sArray.length - 1) sum += Math.min(num1, num2);
}
return sum;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: