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.
class Solution {
List<List<String>> res = new ArrayList<>();
Map<String, Integer> hmp = new HashMap<>();
public List<List<String>> groupAnagrams(String[] strs) {
int Len=0;
for(int i=0; i<strs.length; i++){
findPlace(strs[i]);
}
return res;
}
public void findPlace(String str) {
char[] strC = str.toCharArray();
Arrays.sort(strC);
String StrC = new String(strC);
int index;
if (hmp.containsKey(StrC)) {
index=hmp.get(StrC);
res.get(index).add(str);
} else {
List<String> sub = new ArrayList<>();
sub.add(str);
res.add(sub);
hmp.put(StrC, res.size()-1);
}
}
}
/**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function(strs) {
const len = strs.length
const res = []
const map = new Map()
for (let i = 0; i < len; i++) {
const str = strs[i].split('').sort().join('')
if (!map.has(str)) {
const arr = []
arr.push(strs[i])
map.set(str, arr)
} else {
const arr = map.get(str)
arr.push(strs[i])
map.set(str, arr)
}
}
map.forEach(value => {
res.push(value)
})
return res
};
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
HashMap<String, List<String>> resultMap = new HashMap<>();
List<List<String>> resu = new ArrayList<>();
String[] notSortedCopyOfArr = Arrays.copyOf(strs, strs.length);
for(int i = 0; i< strs.length; i++){
strs[i] = sortString(strs[i]);
}
for(int i = 0; i < strs.length; i++){
List<String> itemsList = resultMap.get(strs[i]);
if(itemsList == null) {
//create new list in case if no other anagrams added
itemsList = new ArrayList<String>();
itemsList.add(notSortedCopyOfArr[i]);
resultMap.put(strs[i], itemsList);
} else {
// add if item is not already in list
itemsList.add(notSortedCopyOfArr[i]);
}
}
for(List<String> value : resultMap.values()){
resu.add(value);
}
return resu;
}
public static String sortString(String inputString) {
char tempArray[] = inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
}