Leetcode 1487. Making File Names Unique (python)

题目

在这里插入图片描述

解法1:暴力TLE

class Solution:
    def getFolderNames(self, names: List[str]) -> List[str]:
        seen = {}
        ans = []
        for name in names:
            if name not in seen:
                ans.append(name)
                seen[name] = True
            else:
                for i in range(1,1000000):
                    new_name = name+'('+ str(i)+')'
                    if new_name not in seen:
                        ans.append(new_name)
                        seen[new_name] = True
                        break
        return ans

解法2:hashmap

改进的点在于更好的利用hashmap
这道题有一个关键点需要想清楚:当遇到之前出现过的名词,我们一定是在这个出现过的名字上加数字进行更新,与其他的名字没有任何关系。想清楚了这点,也就解法很明确了。为了更快的找到需要加的数字,我们及时更新每个名字出现过的次数

class Solution:
    def getFolderNames(self, names: List[str]) -> List[str]:
        # main idea: store the previous appeared names and its appeared times; when see a name, if it has not appeared before, we simply append to the answer; otherwise, we keep updating the name using the previous appeared times of this name
        
        # a dict store the name and appeared times pair
        seen = {}
        ans = []
        
        for name in names:
            # get the number of times that this name previously appeared
            count = seen.get(name,0)
            # save the current name for later update usage
            prev_name = name
            
            # if count>0, means this name has appeared before
            if count>0:
                # we update it use the previous appeared times, until create a new name
                while prev_name in seen:
                    prev_name = name + '('+str(count)+')'
                    count += 1
                # only update the count of the name when the name has appeared previously. update the count of the previous appeared name to count, so we can quickly found the number when we encounter same name
                seen[name] = count
            # the prev_name is now a new name no matter count bigger or smaller than 0, we initialize the count to be 1
            seen[prev_name] = 1
            ans.append(prev_name)
        
        return ans
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值