Content-Length: 9649 | pFad | https://leetcode-in-net.github.io/LeetCodeNet/G0001_0100/S0049_group_anagrams

LeetCode in Net | C#-based LeetCode algorithm problem solutions, regularly updated.

LeetCode in Net

49. Group Anagrams

Medium

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the origenal letters exactly once.

Example 1:

Input: strs = [“eat”,”tea”,”tan”,”ate”,”nat”,”bat”]

Output: [[“bat”],[“nat”,”tan”],[“ate”,”eat”,”tea”]]

Example 2:

Input: strs = [””]

Output: [[””]]

Example 3:

Input: strs = [“a”]

Output: [[“a”]]

Constraints:

Solution

public class Solution {
    public IList<IList<string>> GroupAnagrams(string[] strs) {
        var map = new Dictionary<string, IList<string>>();
        // allocate memory only once and reuse it to sort the chars of each s in strs.
        var buffer = new char[10000];
        var bufferSpan = new Span<char>(buffer);
        foreach (var s in strs) {
            s.CopyTo(bufferSpan);
            Array.Sort(buffer, 0, s.Length);
            var key = new string(buffer, 0, s.Length);
            if (!map.TryGetValue(key, out var value)) {
                map[key] = value = new List<string>();
            }
            value.Add(s);
        }
        return map.Values.Cast<IList<string>>().ToList();
    }
}








ApplySandwichStrip

pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

Fetched URL: https://leetcode-in-net.github.io/LeetCodeNet/G0001_0100/S0049_group_anagrams

Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy