Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

696. Count Binary Substrings #291

Open Tcdian opened 3 years ago

Tcdian commented 3 years ago

696. Count Binary Substrings

给定一个字符串 s,计算具有相同数量01的非空(连续)子字符串的数量,并且这些子字符串中的所有0和所有1都是组合在一起的。

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

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

Tcdian commented 3 years ago

Solution

/**
 * @param {string} s
 * @return {number}
 */
var countBinarySubstrings = function(s) {
    let result = 0;
    let zeroCount = 0;
    let oneCount = 0;
    for (let i = 0; i < s.length; i++) {
        if (s[i] === '0') {
            zeroCount += 1;
        } else {
            oneCount += 1;
        }
        if (i + 1 === s.length || s[i + 1] !== s[i]) {
            result += Math.min(zeroCount, oneCount);
            if (s[i] === '0') {
                oneCount = 0;
            } else {
                zeroCount = 0;
            }
        }
    }
    return result;
};
function countBinarySubstrings(s: string): number {
    let result = 0;
    let zeroCount = 0;
    let oneCount = 0;
    for (let i = 0; i < s.length; i++) {
        if (s[i] === '0') {
            zeroCount += 1;
        } else {
            oneCount += 1;
        }
        if (i + 1 === s.length || s[i + 1] !== s[i]) {
            result += Math.min(zeroCount, oneCount);
            if (s[i] === '0') {
                oneCount = 0;
            } else {
                zeroCount = 0;
            }
        }
    }
    return result;
};