Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 08a3758

Browse files
committed
Add solution #2609
1 parent d913ffe commit 08a3758

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1940,6 +1940,7 @@
19401940
2601|[Prime Subtraction Operation](./solutions/2601-prime-subtraction-operation.js)|Medium|
19411941
2605|[Form Smallest Number From Two Digit Arrays](./solutions/2605-form-smallest-number-from-two-digit-arrays.js)|Easy|
19421942
2606|[Find the Substring With Maximum Cost](./solutions/2606-find-the-substring-with-maximum-cost.js)|Medium|
1943+
2609|[Find the Longest Balanced Substring of a Binary String](./solutions/2609-find-the-longest-balanced-substring-of-a-binary-string.js)|Easy|
19431944
2615|[Sum of Distances](./solutions/2615-sum-of-distances.js)|Medium|
19441945
2618|[Check if Object Instance of Class](./solutions/2618-check-if-object-instance-of-class.js)|Medium|
19451946
2619|[Array Prototype Last](./solutions/2619-array-prototype-last.js)|Easy|
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 2609. Find the Longest Balanced Substring of a Binary String
3+
* https://leetcode.com/problems/find-the-longest-balanced-substring-of-a-binary-string/
4+
* Difficulty: Easy
5+
*
6+
* You are given a binary string s consisting only of zeroes and ones.
7+
*
8+
* A substring of s is considered balanced if all zeroes are before ones and the number of zeroes
9+
* is equal to the number of ones inside the substring. Notice that the empty substring is
10+
* considered a balanced substring.
11+
*
12+
* Return the length of the longest balanced substring of s.
13+
*
14+
* A substring is a contiguous sequence of characters within a string.
15+
*/
16+
17+
/**
18+
* @param {string} s
19+
* @return {number}
20+
*/
21+
var findTheLongestBalancedSubstring = function(s) {
22+
let result = 0;
23+
let zeros = 0;
24+
let ones = 0;
25+
26+
for (let i = 0; i < s.length; i++) {
27+
if (s[i] === '0') {
28+
if (ones > 0) {
29+
zeros = 0;
30+
ones = 0;
31+
}
32+
zeros++;
33+
} else {
34+
if (zeros >= ones + 1) {
35+
ones++;
36+
result = Math.max(result, 2 * ones);
37+
} else {
38+
zeros = 0;
39+
ones = 0;
40+
}
41+
}
42+
}
43+
44+
return result;
45+
};

0 commit comments

Comments
 (0)