49. Group Anagrams

Medium

Problem Description

49. Group Anagrams

Medium


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

 

Example 1:

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

Output:[["bat"],["nat","tan"],["ate","eat","tea"]]

Explanation:

  • There is no string in strs that can be rearranged to form "bat".
  • The strings "nat" and "tan" are anagrams as they can be rearranged to form each other.
  • The strings "ate", "eat", and "tea" are anagrams as they can be rearranged to form each other.

Example 2:

Input:strs = [""]

Output:[[""]]

Example 3:

Input:strs = ["a"]

Output:[["a"]]

 

Constraints:

  • 1 <= strs.length <= 104
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lowercase English letters.

Solution

0049-group-anagrams.java

java
0049-group-anagrams.java
1public class Solution { 2 public List<List<String>> groupAnagrams(String[] strs) { 3 Map<String, List<String>> res = new HashMap<>(); 4 for (String s : strs) { 5 int[] count=new int[26]; 6 for(char c:s.toCharArray()){ 7 count[c-'a']++; 8 } 9 String key=Arrays.toString(count); 10 res.putIfAbsent(key, new ArrayList<>()); 11 res.get(key).add(s); 12 } 13 return new ArrayList<>(res.values()); 14 } 15}
LeetCode Practice