-
-
Save gwpl/11473647ec2cb6fa4127646d25352c4c to your computer and use it in GitHub Desktop.
all postfixes sorted (Rust Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=bda017580640d3b70ea211bec7e9038b )
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
#![allow(dead_code)] | |
// https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=bda017580640d3b70ea211bec7e9038b | |
// Task: sorted postfixes for given list of strings | |
// Example: bcd -> bcd,cd,d | |
// Example: abc,bcd,xyz -> abc,bc,bcd,c,cd,d,xyz,yz,z | |
fn all_postfixes_sorted(arr: &[&str]) -> Vec<String> { | |
let mut postfixes: std::collections::HashSet<String> = std::collections::HashSet::new(); | |
for &w in arr { | |
for start_idx in 0..(w.chars().count()) { | |
let slice: &str = &w[start_idx..]; | |
let w = String::from(slice); | |
postfixes.insert(w); | |
} | |
} | |
let mut r = postfixes.into_iter().collect::<Vec<String>>(); | |
r.sort(); | |
r | |
} | |
fn main() -> Result<(), Box<dyn std::error::Error>> { | |
println!("{:?}", all_postfixes_sorted(&["abc","bcd","xyz"])); | |
Ok(()) | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::*; | |
#[test] | |
fn examples() { | |
assert_eq!(all_postfixes_sorted(&["bcd"]), | |
vec!["bcd","cd","d"]); | |
assert_eq!(all_postfixes_sorted(&["abc","bcd","xyz"]), | |
vec!["abc", "bc", "bcd", "c", "cd", "d", "xyz", "yz", "z"]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment