Skip to main content

rustgym/leetcode/
_791_custom_sort_string.rs

1struct Solution;
2use std::collections::HashMap;
3
4impl Solution {
5    fn custom_sort_string(s: String, t: String) -> String {
6        let mut hm: HashMap<char, usize> = HashMap::new();
7        for (i, c) in s.char_indices() {
8            *hm.entry(c).or_default() = i;
9        }
10        let mut t: Vec<char> = t.chars().collect();
11        t.sort_unstable_by_key(|c| hm.get(c).unwrap_or(&26));
12        t.iter().collect()
13    }
14}
15
16#[test]
17fn test() {
18    let s = "cba".to_string();
19    let t = "abcd".to_string();
20    let res = "cbad".to_string();
21    assert_eq!(Solution::custom_sort_string(s, t), res);
22}