Tuesday, January 3, 2017

Leetcode/各大家--49. Group Anagrams(HashMap)

49. Group Anagrams(HashMap)
  • Difficulty: Medium
https://leetcode.com/problems/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"]
]

Company:Bloomberg Uber Facebook Yelp

思路: Use HashMap to track each anagram as key, and store the strings in values
           The key is fixed for anagrams by sorting string alphabetically(conver toCharArray() & Arrays.sort).
关键字:Sort String,HashMap


public class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        HashMap<String,List<String>>map = new HashMap<String,List<String>>();
        for(String s:strs){
            char[] tmp = s.toCharArray();//sort string
            Arrays.sort(tmp);
            String key = new String(tmp);
            if(!map.containsKey(key)) map.put(key,new ArrayList<String>());
            map.get(key).add(s);
        }
        
        return new ArrayList<List<String>>(map.values());
    }
}

No comments:

Post a Comment