題目
給你一個字符串數組,請你將 字母異位詞 組合在一起。可以按任意順序返回結果列表。
字母異位詞 是由重新排列源單詞的所有字母得到的一個新單詞。
示例 1:
輸入: strs = [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
輸出: [[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]]
示例 2:
輸入: strs = [“”]
輸出: [[“”]]
示例 3:
輸入: strs = [“a”]
輸出: [[“a”]]
答案
這個問題可以使用字典來解決。我們遍歷字符串數組,對于每個字符串,我們將其所有字符放入一個列表,并將這個列表作為字典的值,字符串本身作為字典的鍵。這樣,所有具有相同字母組合的字符串都會被歸類在一起。
以下是解決這個問題的 Python 代碼:
def groupAnagrams(strs): anagram_dict = {} for word in strs: # 將字符串轉換為字符列表,并按字母順序排序 sorted_chars = sorted(list(word)) # 使用排序后的字符列表作為字典的鍵 key = tuple(sorted_chars) if key not in anagram_dict: anagram_dict[key] = [word] else: anagram_dict[key].append(word) 創建一個新的列表,其中每個元素都是一個子列表,子列表中的元素是字母異位詞組 result = [[word for word in group] for key, group in anagram_dict.items()] return result
現在我們可以測試這個函數:
python
strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
print(groupAnagrams(strs)) 輸出: [['bat'], ['nat', 'tan'], ['ate', 'eat', 'tea']] strs = [""]
print(groupAnagrams(strs))
輸出: [['']] strs = ["a"]
print(groupAnagrams(strs))
輸出: [['a']]