49. Group Anagrams

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: All inputs will be in lower-case.

There are question need to ask during interview : all lower case ? mixed ?

public class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        for(String word : strs){

            char[] c = word.toCharArray();
            Arrays.sort(c);
            String hash = new String(c);
            if(map.containsKey(hash)){
                map.get(hash).add(word);
            }else{
                List<String> l = new ArrayList<>();
                l.add(word);
                map.put(hash, l);
            }
        }

        return new ArrayList<List<String>>(map.values());
    }
}
//sort a string.

            char[] c = word.toCharArray();
            Arrays.sort(c);
            String hash = new String(c);
public class Solution {
    Map<String, List<String>> map = new HashMap<>();

    public List<List<String>> groupAnagrams(String[] strs) {
        for(String s : strs){
            char[] c = s.toCharArray();
            Arrays.sort(c); 
            String key = new String(c);
            if(!map.containsKey(key)){
                map.put(key, new ArrayList<>());
            }
            map.get(key).add(s);
        }

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

results matching ""

    No results matching ""