Skip to content

Instantly share code, notes, and snippets.

@gwpl
Forked from rust-play/playground.rs
Last active July 12, 2021 11:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gwpl/11473647ec2cb6fa4127646d25352c4c to your computer and use it in GitHub Desktop.
Save gwpl/11473647ec2cb6fa4127646d25352c4c to your computer and use it in GitHub Desktop.
#![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