1、題目鏈接
https://leetcode.com/problems/group-anagrams/
2、解題思路
這道題的意思是給你一個字符串?dāng)?shù)組,讓你把含有相同字符的字符串(不考慮字符的順序)進(jìn)行分組,一開始我的想法是遍歷整個數(shù)組胧洒,然后將每個字符串按照字典序排序,然后再把分組中的字符串按照字典序排序墨状,最后比較兩個字符串卫漫,如果相同就把他加到該組當(dāng)中,如果不相同那就新建分組肾砂,毫無疑問這樣做是能實現(xiàn)的列赎,但是TLE(Time Limit Exceed)了,既然超時了镐确,那就找找原因唄包吝,排序可能會導(dǎo)致,兩個for循環(huán)也可能會導(dǎo)致源葫,剛開始除了兩個for循環(huán)我還真沒想到什么好的方法诗越,然后我就考慮將排序給干掉,能不能不排序就知道兩個字符串的字符想不相同呢息堂?那肯定是有的了嚷狞,按照以往的經(jīng)驗块促,碰到這種明目張膽提示了你只有小寫字母(26個字符)的,那就肯定是要逼你用一個int數(shù)組來保存字符串中某個字符出現(xiàn)的次數(shù)床未,但是很不幸竭翠,又超時了,WTF薇搁,后來想到HashMap中的key是不能重復(fù)的斋扰,這不正好和我們的結(jié)果是一樣的嗎,key就是我們結(jié)果中的每一組的共同點(開頭我們說過啃洋,字典序是一樣的)传货,所以,又要排序嗎宏娄?NO损离,剛?cè)サ舻呐判蛭也荒茏约捍蜃约旱哪?gt;_<,最后還是借助我們的字符數(shù)組來完成這一操作了(其實我覺得這么做的結(jié)果也是排序绝编,真香系列),是不是又多了一種字典序排列的方法貌踏。
3十饥、代碼
- Java
private static List<List<String>> groupAnagrams(String[] strs) {
if (null == strs) return null;
List<String> list;
Map<String, List<String>> mapList = new HashMap<>();
for (String s : strs) {
int[] chArray = new int[26];
for (int i = 0; i < s.length(); i++) {
chArray[s.charAt(i) - 97]++;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < chArray.length; i++) {
int chCount = chArray[i];
while (chCount > 0) {
sb.append((char) i + 97);
chCount--;
}
}
String key = sb.toString();
if (mapList.containsKey(key)) {
mapList.get(key).add(s);
} else {
list = new ArrayList<>();
list.add(s);
mapList.put(key, list);
}
}
return new ArrayList<>(mapList.values());
}
- Python
def groupAnagrams(self,strs):
resultMap = {}
for str in strs:
chArray = [0] * 26
for ch in str:
chArray[ord(ch) - 97] += 1
key = ""
for index in range(len(chArray)):
count = chArray[index]
while count > 0:
key += chr(index + 97)
count -= 1
if resultMap.has_key(key):
resultMap.get(key).append(str)
else:
resultMap[key] = [str]
return resultMap.values()
- JavaScript
/**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function(strs) {
let resultMap = {};
for (let j = 0; j < strs.length; j++) {
let chArray = new Array(26);
chArray.fill(0);
for (let i = 0; i < strs[j].length; i++) {
chArray[strs[j].charAt(i).charCodeAt() - 97]++;
}
let key = ""
for (let i = 0; i < chArray.length; i++) {
let count = chArray[i]
while (count > 0) {
key += String.fromCharCode(i + 97)
count--
}
}
if (resultMap.hasOwnProperty(key)) {
resultMap[key].push(strs[j])
} else {
resultMap[key] = [strs[j]]
}
}
let resultList = []
for (let key in resultMap) {
resultList.push(resultMap[key])
}
return resultList
};
4、提交結(jié)果
image