Group Anagrams By Sorted Chars

Sort each word chars into a shared signature, then group with the entry API so anagrams land in one bucket keyed by sorted letters.

RustData Integrity

Code

rustsnippet
23 lines
use std::collections::BTreeMap;

// sorted chars 就是同一组 anagrams 的公共签名:字母相同则排序结果相同
fn signature(word: &str) -> String {
    let mut chars: Vec<char> = word.chars().collect();
    chars.sort_unstable();
    chars.into_iter().collect()
}

fn group_anagrams(words: &[&str]) -> BTreeMap<String, Vec<&str>> {
    let mut groups: BTreeMap<String, Vec<&str>> = BTreeMap::new();
    for word in words {
        groups.entry(signature(word)).or_default().push(word);
    }
    groups
}

fn main() {
    let words = ["listen", "google", "silent", "enlist"];
    for (signature, group) in group_anagrams(&words) {
        println!("{signature}: {group:?}");
    }
}

How it works

The moving parts are the functions signature, group_anagrams and main.

The file repeats itself only inside for word in words.

Caveats

  • The runtime is the only requirement — no packages, no install.

Using it

The main signature reads fn signature(word: &str) -> String

Running the file executes main, which drives group_anagrams in order.

Key statements

fn group_anagrams(words: &[&str]) -> BTreeMap<String, Vec<&str>> {
    let mut groups: BTreeMap<String, Vec<&str>> = BTreeMap::new();
    for word in words {
        groups.entry(signature(word)).or_default().push(word);
    }
    groups
}
let mut chars: Vec<char> = word.chars().collect();
chars.into_iter().collect()
}

Interactive Tools for This Topic

FAQ

How do you run Group Anagrams By Sorted Chars?
It runs as-is — treat the file as the whole program and execute it.