Skip to content

Commit

Permalink
Added custom sort string solution.
Browse files Browse the repository at this point in the history
  • Loading branch information
jusexton committed Jul 28, 2024
1 parent 3704f9c commit e851811
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
24 changes: 24 additions & 0 deletions src/leetcode/custom_sort.rs
Original file line number Diff line number Diff line change
@@ -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)
}
}
1 change: 1 addition & 0 deletions src/leetcode/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,4 @@ mod max_repeating_substr;
mod freq_sort;
mod sort_jumbled_numbers;
mod max_binary_number;
mod custom_sort;

0 comments on commit e851811

Please sign in to comment.