Code shared from the Rust Playground
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)] | |
// 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); | |
} | |
} | |
//TODO: sort them | |
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