-
Notifications
You must be signed in to change notification settings - Fork 21
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add problem 2405: Optimal Partition of String
- Loading branch information
Showing
3 changed files
with
66 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
47 changes: 47 additions & 0 deletions
47
src/problem_2405_optimal_partition_of_string/bit_manipulation.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
pub struct Solution; | ||
|
||
// ------------------------------------------------------ snip ------------------------------------------------------ // | ||
|
||
impl Solution { | ||
pub fn partition_string(s: String) -> i32 { | ||
let mut iter = s.bytes(); | ||
let mut c = iter.next().unwrap(); | ||
let mut used = 0_u32; | ||
let mut result = 1; | ||
|
||
loop { | ||
let probe = 1 << (c - b'a'); | ||
|
||
if used & probe == 0 { | ||
used |= probe; | ||
} else { | ||
result += 1; | ||
used = probe; | ||
} | ||
|
||
if let Some(next) = iter.next() { | ||
c = next; | ||
} else { | ||
break; | ||
} | ||
} | ||
|
||
result | ||
} | ||
} | ||
|
||
// ------------------------------------------------------ snip ------------------------------------------------------ // | ||
|
||
impl super::Solution for Solution { | ||
fn partition_string(s: String) -> i32 { | ||
Self::partition_string(s) | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
#[test] | ||
fn test_solution() { | ||
super::super::tests::run::<super::Solution>(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
pub mod bit_manipulation; | ||
|
||
pub trait Solution { | ||
fn partition_string(s: String) -> i32; | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::Solution; | ||
|
||
pub fn run<S: Solution>() { | ||
let test_cases = [("abacaba", 4), ("ssssss", 6)]; | ||
|
||
for (s, expected) in test_cases { | ||
assert_eq!(S::partition_string(s.to_string()), expected); | ||
} | ||
} | ||
} |