pub fn condense(str: &str) -> StringExpand description
Removes all duplicate characters from a string, preserving the first occurrence of each.
This function iterates through the input string and builds a new string containing only
the first occurrence of each character, maintaining the original order. It uses a HashSet
to track which characters have already been encountered.
§Algorithm
- Create an empty
HashSetto track seen characters - Create an empty result
String - For each character in the input:
- If the character hasn’t been seen (insert returns true), append it to the result
- If the character has been seen (insert returns false), skip it
- Return the result string
§Arguments
str- A string slice to be condensed
§Returns
A new String with all duplicate characters removed, preserving the order of first occurrences
§Examples
use old_crypto_rs::helpers::condense;
// Simple duplicates
let result = condense("AAAAA");
assert_eq!(result, "A");
// Mixed duplicates
let result = condense("ARABESQUE");
assert_eq!(result, "ARBESQU");
// Longer string with duplicates
let result = condense("ARABESQUEABCDEFGHIKLMNOPQRSTUVWXYZ");
assert_eq!(result, "ARBESQUCDFGHIKLMNOPTVWXYZ");
// No duplicates
let result = condense("ABCDE");
assert_eq!(result, "ABCDE");§Performance
Time complexity: O(n) where n is the length of the input string Space complexity: O(k) where k is the number of unique characters
§See Also
condense_str- An optimized version using a bitset for ASCII characters