MrainW's Home

All things come to those who wait!

0%

LeetCode 41. First Missing Positive

Question

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

https://leetcode.com/problems/group-anagrams/

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
ArrayList<List<String>> res = new ArrayList<List<String>>();
if (strs == null || strs.length == 0) return res;
HashMap<String, List<String>> map = new HashMap<>();
for (int i = 0; i < strs.length; i++) {
char[] curr = strs[i].toCharArray();
Arrays.sort(curr);
String key = String.valueOf(curr);
if (!map.containsKey(key))
map.put(key, new ArrayList<String>());
map.get(key).add(strs[i]);
}
res = new ArrayList<List<String>>(map.values());
return res;
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(n)

Welcome to my other publishing channels