字母异位词分组 - 中等

*************

Python

topic: 49. 字母异位词分组 - 力扣(LeetCode)

*************

Give the topic an inspection.

I have some dreams in the past few nights. People dead every time and I donot know why. Maybe the new room need some time to suit. And maybe I should replace the bed to reduce the night dream. 

Back to the topic. I tried this topic before but now, I can hardly tell what to do to figure it out. And deepseek says hash need to be used. The basic usage of hash should be learned angain.

The basic form of hash table is {键: 值}, which is {Key: Value}. key is kind of identify. The type of key in the hash tabe is required to be same. The value of the hash table is not.

contacts = 
{
    "老王": "13800138000",
    "急救": "120",                # 键是字符串,值是字符串
    "火警": 119,                  # 键是字符串,值是数字(注意:119没有引号,是数字)
    "苹果": 5.8,                  # 水果价格(浮点数)
    "courses": ["数学", "英语"]   # 列表
}

I am gonna tell you some stories. No big deal, just some stories. The protagonist is Scarlett.

1. Scarlett is learning chinese

Scarelett wanna learn some chinese so that she chases me in chinese. And, of course, I will make her a dictionary.

word_dict = 
{
    "I"        : "我",
    "love"     : "爱",
    "elseWhere": "在别处"
}

print(word_dict["elseWhere"])  # 输出: "在别处"

2. Statistic

When Scarlett cannot get in touch with me, she will be troubled in doubt: he loves me, he loves me not...

votes = ["他想我", "他想我", "他不想我", "他想我", "他不想我", "他想我"]
vote_count = {}

for name in votes:
    if name in vote_count:
        vote_count[name] += 1
    else:
        vote_count[name] = 1

print(vote_count)  # 输出: {'他想我': 3, '他不想我': 2}

3. Scarlett got my number

And with no doubt, Scarlett got my number.

phone_book = 
{
    "小红"  : "13800138000",
    "小明"  : "13900139000",
    "在别处": "5201314"  
}

print(phone_book["在别处"])  # 输出: "5201314"

4. Scarlett and me go to the museum

Today is the museum day. And actuaklly I do like museums. The security will check the ids.

registered_ids = set()  # 集合就是只有键的哈希表
ids = [101, 102, 138, 138]  # ID列表

for id in ids:
    if id in registered_ids:
        print(f"学号 {id} 重复了!")
    else:
        registered_ids.add(id)

print(registered_ids)  

# 输出:
学号 138 重复了!
{101, 102, 138}

5. Group data

Scarlett and me save some money in the bank. And we are going to travel. We manage our deposit accounts. Some for travellig, some for education.

scores = [("旅行", 90000), ("买房", 8500), ("买车", 9200), ("情趣用品", 7000)]
score_groups = {}  # 空字典

for name, score in scores:
    if score >= 90:
        group = "优秀"
    elif score >= 80:
        group = "良好"
    else:
        group = "及格"
    
    # 关键点:需要检查键是否已存在
    if group in score_groups:
        score_groups[group].append(name)  # 如果键存在,直接追加
    else:
        score_groups[group] = [name]      # 如果键不存在,先初始化列表

print(score_groups)
输出:


{
    '优秀': ['旅行', '买车'],
    '良好': ['买房'],
    '及格': ['情趣用品']
}

 That is the basic usage of hash table.

Back to the topic, the first thing  is to creat a hash tabkle.\

class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        # 创建一个空的哈希表,用来分类
        groups = {}

        

then sort the word next.

class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        # 创建一个空的哈希表,用来分类
        groups = {}

        sorted_letters = sorted(word)            # 字母排序,例如 "tea" -> ['a', 'e', 't']
        key            = ''.join(sorted_letters) # 合并的字符串作为键,"aet"

Then groups.

class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        # 创建一个空的哈希表,用来分类
        groups = {}

        for word in strs:
            sorted_letters = sorted(word)            # 字母排序,例如 "tea" -> ['a', 'e', 't']
            key            = ''.join(sorted_letters) # 合并的字符串作为键,"aet"

            if key in groups:
                groups[key].append(word) # 在键对应的后面,即值上加上排序前的单词
            else:
                groups[key] = [word] # 如果排序后的单词在列表里没存在过,那么就加入他作为键

        return list(groups.values())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值