Skip to content

Commit c49aa74

Browse files
authored
Create 2609-find-the-longest-balanced-substring-of-a-binary-string.js
1 parent 74d4350 commit c49aa74

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* @param {string} s
3+
* @return {number}
4+
*/
5+
const findTheLongestBalancedSubstring = function(s) {
6+
let res = 0
7+
8+
const n = s.length
9+
for(let i = 0; i < n - 1; i++) {
10+
for(let j = i + 1; j < n; j++) {
11+
const str = s.slice(i, j + 1)
12+
if(valid(str)) {
13+
res = Math.max(res, str.length)
14+
}
15+
}
16+
}
17+
18+
return res
19+
20+
function valid(str) {
21+
let res = true
22+
const len = str.length
23+
if(len % 2 === 1) return false
24+
const lastZeroIdx = str.lastIndexOf('0')
25+
const firstOneIdx = str.indexOf('1')
26+
27+
return firstOneIdx - lastZeroIdx === 1 && len / 2 === firstOneIdx
28+
}
29+
};

0 commit comments

Comments
 (0)