【竞赛题】6362. 最长平衡子字符串 (JavaScript版)
题目:
给你一个仅由 0 和 1 组成的二进制字符串 s 。
如果子字符串中 所有的 0 都在 1 之前 且其中 0 的数量等于 1 的数量,则认为 s 的这个子字符串是平衡子字符串。请注意,空子字符串也视作平衡子字符串。
返回 s 中最长的平衡子字符串长度。
子字符串是字符串中的一个连续字符序列。
示例 1:
输入:s = “01000111”
输出:6
解释:最长的平衡子字符串是 “000111” ,长度为 6 。
示例 2:
输入:s = “00111”
输出:4
解释:最长的平衡子字符串是 “0011” ,长度为 4 。
示例 3:
输入:s = “111”
输出:0
解释:除了空子字符串之外不存在其他平衡子字符串,所以答案为 0 。
提示:
1 <= s.length <= 50
‘0’ <= s[i] <= ‘1’
较为完美的答案:
/* @param {string} s* @return {number}*/
var findTheLongestBalancedSubstring = function(s) {let len = s.lengthconst array = s.split('')let max = 0;for(let i = 0; i < len; i++) {if (i > 0 && array[i] === '1' && array[i-1] === '0') {max = Math.max(max, find(i, array))}}return max
};
function find(i, array) {let start = i-1let end = ilet count = 0console.log(i, array)while(start >= 0 && end <= array.length) {if (array[start]=== '0' && array[end] === '1') {count += 2start = start - 1end = end + 1}else {break;}}return count
}
初次参赛答案:
/* @param {string} s* @return {number}*/
function statis (s, index, count = 1, current = '0') {const obj = {index,count}if (index+1 < s.length -1 && s[index+1] === current) {return statis(s, index+1, count+1, current)}return obj
}
var findTheLongestBalancedSubstring = function(s) {if (s.indexOf('0') === -1 || s.indexOf('1') === -1) return 0const zeroObj = {} // key是起始0,index是中止0,count是总计let len = s.lengthfor (let i = 0; i < len-1; i++) {const item = Number(s[i])if ([0].includes(item)) {const obj = statis(s, i)zeroObj[i] = obji = obj.index}}let count = 0; // 临时总数let max = 0; // 最大值console.log(zeroObj)
// { '0': { index: 0, count: 1 }, '2': { index: 4, count: 3 } }Object.keys(zeroObj).forEach(it => {const item = zeroObj[it]count = 0;for (let j=1; j<item.count+1; j++) {console.log((item.index + j < len-1), s[item.index + j] === '1', item.index + j)if ((item.index + j < len) && s[item.index + j] === '1') {count = count + 1} else {break;}}if (max < count) {max = count}})return max*2
};