696. Count Binary Substrings

来源:互联网 发布:iphone flac 播放软件 编辑:程序博客网 时间:2024/05/17 22:40

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: 6Explanation: 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.

思路:
这题简单粗暴的做法就是O(n^2)的复杂度下,依次判断以每一个字符为起点的substring是否存在我们要找的group,这里有一个默认的依据就是,每个位置的字符最多只会成为一个group的开头(结尾)。可以反证,如果不是得话,一定不满足group的要求。所以这种暴力解法理论上是正确的,但是leetcode有时间限制,这种解法超时了。
这里提供一种O(n)的解法。
trick在于,这个substring是binary的,所以我们只需要判断前后连续的0和1的个数是否满足要求就行。具体代码如下:

class Solution {public:    int countBinarySubstrings(string s) {        int len = s.length();        char first = s[0];        int cnt0 = 0;        int cnt1 = 0;        int count = 0;        for (int i = 0; i < len; i++) {            if (s[i] != first) {                first = s[i];                if (first == '1')                    cnt1 = 0;                else                     cnt0 = 0;            }            if (s[i] == '1') {                cnt1++;                if (cnt1 <= cnt0) count++;            }            if (s[i] == '0') {                cnt0++;                if (cnt0 <= cnt1) count++;            }        }        return count;    }};