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 438. Find All Anagrams in a StringLeetCode
- LeetCode|劍指 Offer 49.醜數LeetCode
- LeetCode 49. 字母異位詞分組LeetCode
- [LeetCode] Group AnagramLeetCode
- (轉)leetcode:Find All Anagrams in a String 滑動視窗方法總結LeetCode
- Leetcode 25 Reverse Nodes in k-GroupLeetCode
- 【Leetcode】25.Reverse Nodes in k-GroupLeetCode
- [Leetcode力扣 25] Reverse Nodes in k-GroupLeetCode力扣
- [LeetCode] 2134. Minimum Swaps to Group All 1s Together IILeetCode
- 劍指offer—49.醜數—分析及程式碼(Java)Java
- group conv
- 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 優化優化
- Linq使用Group By 1
- 04-dispatch_group
- SAP Purchasing Group in DetailsAI
- 7.98 GROUP_ID
- group by 查詢原理
- Group by 最佳化
- ERP的Account group和CRM partner group的對映關係
- Exchange - Add Owner of Distribution Group
- MySQL group replication介紹MySql
- odoo group by 彙總功能Odoo
- three.js之GroupJS
- MASM中Group的作用ASM
- max() group by共用問題
- GCD 中Group的使用GC
- GCD(三) dispatch_groupGC
- [20220124]group by bug.txt
- group by event_name, operation
- PostgreSQL DBA(186) - SQL Group BySQL
- group by分組查詢
- group by 和 order by 一起使用,報錯 ORA-00979:不是 GROUP BY 表示式
- Availability Group On Linux 搭建後記AILinux