Skip to content

Instantly share code, notes, and snippets.

@mykhailokrainik
Created July 13, 2018 12:34
Show Gist options
  • Save mykhailokrainik/9b14c3bd672cfcaea3a0e50504eb8779 to your computer and use it in GitHub Desktop.
Save mykhailokrainik/9b14c3bd672cfcaea3a0e50504eb8779 to your computer and use it in GitHub Desktop.
Remove duplicate words
// Remove duplicate words
// Your task is to remove all duplicate words from string, leaving only single words entries.
// Example:
// Input:
// 'alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta'
// Output:
// 'alpha beta gamma delta'
fn remove_duplicate_words(s: &str) -> String {
let r = s.split(" ").fold(String::from(""), |mut r, a| {
if !r.contains(a) {
r.push_str(&format!("{} ", a));
}
r
});
r.trim().to_string()
}
#[test]
fn sample_test_cases() {
assert_eq!(remove_duplicate_words("alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta"), "alpha beta gamma delta");
assert_eq!(remove_duplicate_words("my cat is my cat fat"), "my cat is fat");
}
@mykhailokrainik
Copy link
Author

Known Issues:

  1. String.contains will find any match, will must rewrite methods that check for a complete match.
  2. Use type Vec and join() instead type String and push to avoid trim() for result value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment