49. Group Anagrams (Medium)

https://leetcode.com/problems/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.

Solutions


class Solution {

    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> ans = new ArrayList<>();
        if (strs == null || strs.length == 0) {
            return ans;
        }

        Map<String, List<String>> map = new HashMap<>();

        for (int i = 0; i < strs.length; i++) {
            String s = sort(strs[i]);
            if (!map.containsKey(s)) {
                map.put(s, new ArrayList<>());
            }

            map.get(s).add(strs[i]);
        }

        for (String key : map.keySet()) {
            ans.add(map.get(key));
        }

        return ans;
    }

    private String sort(String s) {
        if (s == null) {
            return null;
        }

        if (s.length() == 1) {
            return s;
        }

        char[] chars = s.toCharArray();
        Arrays.sort(chars);

        String ans = "";
        for (int i = 0; i < chars.length; i++) {
            ans += chars[i];
        }

        return ans;
    }
}

Incorrect Solutions

References

Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-12-03 11:01:18

results matching ""

    No results matching ""