Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created July 12, 2021 09:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rust-play/db138e144c4e6682def63dad59536170 to your computer and use it in GitHub Desktop.
Save rust-play/db138e144c4e6682def63dad59536170 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#![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