【leetcode每日刷题】49. Group Anagrams

Given an array of strings, group anagrams together.

Example:

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

Note:

  • All inputs will be in lowercase.
  • The order of your output does not matter.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Arrays;

class num49{
    public static void main(String[] args) {
        String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
        List> list = num49.groupAnagrams(strs);
        for(List strlist:list){
            for(Object s:strlist){
                System.out.print(s+" ");
            }
            System.out.println('\n');
        }
    }
   // 对每一个字符串进行排序的方法
    public static List> groupAnagrams1(String[] strs) {
        Map> map = new HashMap>();
        for(int i=0; i());
            }
            map.get(key).add(strs[i]);
        }
        return new ArrayList(map.values());
    }
    // 使用字符数组的方法
    public static List> groupAnagrams2(String[] strs) {
        Map> map = new HashMap>();
        for(String str: strs){
            int[] count = new int[26];
            for(int i=0; i list = new ArrayList<>();
                list.add(str);
                map.put(key, list);
            }else{
                map.get(key).add(str);
            }
        }
        return new ArrayList(map.values());
    }
}

 

你可能感兴趣的:(leetcode刷题,java)