leetcode | Group Anagrams

1196 단어 LeetCode
Given an array of strings, group anagrams together.
For example, given:  ["eat", "tea", "tan", "ate", "nat", "bat"] ,  Return:
[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Note:
For the return value, each inner list's elements must follow the lexicographic order.
All inputs will be in lower-case.
public class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Arrays.sort(strs);
        HashMap<String,ArrayList<String>> hashMap = new HashMap<String, ArrayList<String>>();
        for (int i = 0; i < strs.length; i++) {
            char[] charArray = strs[i].toCharArray();
            Arrays.sort(charArray);
            String temp = new String(charArray);
            if(!hashMap.containsKey(temp))
                hashMap.put(temp, new ArrayList<String>());
            hashMap.get(temp).add(strs[i]);
                

        }
		return new ArrayList<List<String>>(hashMap.values());

    }
}

좋은 웹페이지 즐겨찾기