Skip to content

Commit bfd1596

Browse files
committed
Add problem 2609: Find the Longest Balanced Substring of a Binary String
1 parent 5447fc1 commit bfd1596

File tree

3 files changed

+73
-0
lines changed

3 files changed

+73
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1926,6 +1926,7 @@ pub mod problem_2598_smallest_missing_non_negative_integer_after_operations;
19261926
pub mod problem_2600_k_items_with_the_maximum_sum;
19271927
pub mod problem_2601_prime_subtraction_operation;
19281928
pub mod problem_2602_minimum_operations_to_make_all_array_elements_equal;
1929+
pub mod problem_2609_find_the_longest_balanced_substring_of_a_binary_string;
19291930

19301931
#[cfg(test)]
19311932
mod test_utilities;
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
pub fn find_the_longest_balanced_substring(s: String) -> i32 {
7+
let mut zero_length = 0_u8;
8+
let mut iter = s.bytes();
9+
let mut result = 0;
10+
11+
'outer: while let Some(c) = iter.next() {
12+
if c == b'0' {
13+
zero_length += 1;
14+
} else {
15+
let mut one_length = 1;
16+
17+
loop {
18+
if let Some(c) = iter.next() {
19+
if c == b'0' {
20+
result = result.max(zero_length.min(one_length));
21+
zero_length = 1;
22+
23+
break;
24+
}
25+
26+
one_length += 1;
27+
} else {
28+
result = result.max(zero_length.min(one_length));
29+
30+
break 'outer;
31+
}
32+
}
33+
}
34+
}
35+
36+
i32::from(result * 2)
37+
}
38+
}
39+
40+
// ------------------------------------------------------ snip ------------------------------------------------------ //
41+
42+
impl super::Solution for Solution {
43+
fn find_the_longest_balanced_substring(s: String) -> i32 {
44+
Self::find_the_longest_balanced_substring(s)
45+
}
46+
}
47+
48+
#[cfg(test)]
49+
mod tests {
50+
#[test]
51+
fn test_solution() {
52+
super::super::tests::run::<super::Solution>();
53+
}
54+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
pub mod iterative;
2+
3+
pub trait Solution {
4+
fn find_the_longest_balanced_substring(s: String) -> i32;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
11+
pub fn run<S: Solution>() {
12+
let test_cases = [("01000111", 6), ("00111", 4), ("111", 0)];
13+
14+
for (s, expected) in test_cases {
15+
assert_eq!(S::find_the_longest_balanced_substring(s.to_string()), expected);
16+
}
17+
}
18+
}

0 commit comments

Comments
 (0)