leetcode-1487-保证文件名唯一

题目描述:

 

第一次提交: 有错 未找出问题 留坑

class Solution:
    def getFolderNames(self, names: List[str]) -> List[str]:
  
        res = []
        dic = collections.Counter()
        for name in names:
            if name not in dic:
                res.append(name)
                dic[name] += 1
            else:
                tmp = name + '(' + str(dic[name]) + ')'
                while(tmp in dic):
                    dic[name] += dic[tmp]
                    tmp = name + '(' + str(dic[name]) + ')'
                dic[tmp]+=1
                res.append(tmp)
                dic[name] += 1
        return res

 方法:

class Solution:
    def getFolderNames(self, names: List[str]) -> List[str]:
        dict = {}
        ans = []
        for name in names:
            if name not in dict:
                dict[name] = 0
                ans.append(name)
            else:
                dict[name] += 1
                new_name = '%s(%d)'%(name, dict[name])
                while new_name in dict:
                    dict[name] += 1
                    new_name = '%s(%d)'%(name, dict[name])
                dict[new_name] = 0
                ans.append(new_name)
        return ans
    

猜你喜欢

转载自www.cnblogs.com/oldby/p/13191118.html