LeetCode 49. Group Anagrams
一、 問題描述:
Given an array of strings, groupanagrams 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
二、 問題分析:
給定一個元素為字串的列表,要求把具有相同字元不同排序方法的字串歸類在同一列表,輸出元素為字串歸類列表的列表。
例如題目所給的樣例:
["eat", "tea", "tan", "ate","nat", "bat"]
因為"ate","eat","tea" 具有相同字元但字元排序方法不同,所以將它們歸類在同一列表:["ate","eat","tea"]
同樣,"tan" 和 "nat" 也屬於相同字元不同排列順序,所以也將它們歸類在同一列表:["nat","tan"]
而最後只剩下 "bat" 唯一一個元素,所以將它單獨歸類為一個列表:["bat"]
因此,最後輸出列表為:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
三、 演算法設計:
假設輸入列表為q,定義一個字典d,對q中的每個字串str元素進行以下操作:
對str進行字典順序排序獲得新字串nstr,在d中搜尋是否存在以nstr為鍵,值為列表的元素:①如果存在,則將str加入該列表中;②如果不存在,則在d中建立一個以nstr為鍵,值為僅包含str的列表的元素
返回d的值列表,即為目的結果:元素為字串歸類列表的列表
四、 程式實現:
class Solution:
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
n = len(strs)
strss = []
dic = {}
for s in strs:
temp = list(s);
temp.sort()
temp = ''.join(temp)
if temp not in dic.keys():
dic[temp] = [s]
else:
dic[temp].append(s)
return list(dic.values())
相關文章
- Leetcode 49 Group AnagramsLeetCode
- Leetcode AnagramsLeetCode
- Leetcode-AnagramsLeetCode
- Anagrams leetcode javaLeetCodeJava
- LeetCode|劍指 Offer 49.醜數LeetCode
- LeetCode 49. 字母異位詞分組LeetCode
- LeetCode 438. Find All Anagrams in a StringLeetCode
- [LeetCode] Group AnagramLeetCode
- (轉)leetcode:Find All Anagrams in a String 滑動視窗方法總結LeetCode
- LeetCode-Group Shifted StringsLeetCode
- Leetcode Reverse Nodes in k-GroupLeetCode
- Leetcode 25 Reverse Nodes in k-GroupLeetCode
- Leetcode-Reverse Nodes in k-GroupLeetCode
- Reverse Nodes in k-Group leetcode javaLeetCodeJava
- 【Leetcode】25.Reverse Nodes in k-GroupLeetCode
- [Leetcode力扣 25] Reverse Nodes in k-GroupLeetCode力扣
- 劍指offer—49.醜數—分析及程式碼(Java)Java
- [LeetCode] 2134. Minimum Swaps to Group All 1s Together IILeetCode
- [CareerCup] 11.2 Sort Anagrams Array 異位詞陣列排序陣列排序
- Oracle GroupOracle
- [LeetCode] Reverse Nodes in k-Group 每k個一組翻轉連結串列LeetCode
- group_replication_bootstrap_group 用於什麼boot
- 資料庫的sort group by和hash group by資料庫
- oracle partition by group by,詳解partition by和group by對比Oracle
- MySQL Group ReplicationMySql
- Group by 優化優化
- Oracle Hash Group ByOracle
- sql用法——group bySQL
- Oracle group by使用Oracle
- ORA-00937: not a single-group group functionFunction
- oracle全文索引之SECTION GROUP_6_PATH_SECTION_GROUPOracle索引
- oracle全文索引之SECTION GROUP_5_AUTO_SECTION_GROUPOracle索引
- oracle全文索引之SECTION GROUP_4_XML_SECTION_GROUPOracle索引XML
- oracle全文索引之SECTION GROUP_3_HTML_SECTION_GROUPOracle索引HTML
- oracle全文索引之SECTION GROUP_2_BASIC_SECTION_GROUPOracle索引
- oracle全文索引之SECTION GROUP_1_NULL_SECTION_GROUPOracle索引Null
- group by 查詢原理
- group by 排序問題排序