696. Count Binary Substrings 計數二進制子字符串
阿新 • • 發佈:2017-10-18
cti har ati 為知 http number cut str 1.4
給一個字符串s,計算具有相同數字0和1的非空(連續)子字符串的數量,並且這些子字符串中的所有0和所有1都被連續分組。 發生多次的子字符串將被計數它們發生的次數。
來自為知筆記(Wiz)
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.
/**
* @param {string} s
* @return {number}
*/
var countBinarySubstrings = function (s) {
let prevRunLength = 0;
let curRunLength = 1;
let res = 0;
for (let i = 1; i < s.length; i++) {
if (s[i] == s[i - 1]) {
curRunLength++;
} else {
prevRunLength = curRunLength;
curRunLength = 1;
}
if (prevRunLength >= curRunLength) res++;
}
return res;
};
//console.log(countBinarySubstrings("00110011"));
來自為知筆記(Wiz)
696. Count Binary Substrings 計數二進制子字符串