diff --git a/README.md b/README.md index 380f70c..9b90a06 100644 --- a/README.md +++ b/README.md @@ -147,6 +147,7 @@ other languages. - Sort Colors (https://leetcode.com/problems/sort-colors) - Rotate Digits (https://leetcode.com/problems/rotated-digits) - Sort Jumbled Numbers (https://leetcode.com/problems/sort-the-jumbled-numbers) +- Custom Sort String (https://leetcode.com/problems/custom-sort-string) ### Other diff --git a/src/leetcode/custom_sort.rs b/src/leetcode/custom_sort.rs new file mode 100644 index 0000000..a780b95 --- /dev/null +++ b/src/leetcode/custom_sort.rs @@ -0,0 +1,24 @@ +pub fn custom_sort_string(order: String, mut s: String) -> String { + let order = order.char_indices().fold([0; 26], |mut acc, (idx, c)| { + acc[c as usize - 'a' as usize] = idx; + acc + }); + unsafe { + s.as_mut_vec() + .sort_by_key(|c| order[*c as usize - 'a' as usize]) + }; + s +} + +#[cfg(test)] +mod tests { + use super::custom_sort_string; + + #[test] + fn sorts_in_custom_order() { + let order = "cba".to_string(); + let s = "abc".to_string(); + let result = custom_sort_string(order, s); + assert_eq!("cba".to_string(), result) + } +} diff --git a/src/leetcode/mod.rs b/src/leetcode/mod.rs index 248b19f..78f37a0 100644 --- a/src/leetcode/mod.rs +++ b/src/leetcode/mod.rs @@ -50,3 +50,4 @@ mod max_repeating_substr; mod freq_sort; mod sort_jumbled_numbers; mod max_binary_number; +mod custom_sort;