Group Anagrams

Given an array of strings, group anagrams together.

Click this link to try it on Leetcode

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.

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
  if (strs.length == 0) return new ArrayList();
        Map<String, List> ans = new HashMap<String, List>();
        for (String s : strs) {
            char[] ca = s.toCharArray();
            Arrays.sort(ca);
            String key = String.valueOf(ca);
            if (!ans.containsKey(key)) ans.put(key, new ArrayList());
            ans.get(key).add(s);
        }
        return new ArrayList(ans.values());
    }
}


Here string is to be stored as a key to check whether the same string is already present or not. For comparison of string , it is to be converted to character array and sort it and compare it with other strings.


For more Leetcode Problems

Comments

Popular posts from this blog

Balanced Binary Tree

Majority Element

First Unique Character in a String

Smallest Range II