49. Group Anagrams

problem description

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.

algorithm thought

找出有相同字符,顺序不一样的所有字符串,然后返回他们的集合。这里有一种最简单的办法确定-sort。将所有的字符串sort一下,排序之后相等的字符串,就可以认定为一个group。

code

algorithm analysis

假定有n个字符串,每个字符串平均长度是m,对每个字符排序时间复杂度是O(nlgn),两个字符串比较时间复杂度是O(n),然后需要定义一个hashmap保存之前遍历的字符串的结果。最后时间复杂度是O(m*nlgn)

Last updated