题目
解法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] = Trueelse:for i in range(1,1000000):new_name = name+'('+ str(i)+')'if new_name not in seen:ans.append(new_name)seen[new_name] = Truebreakreturn 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 pairseen = {
}ans = []for name in names:# get the number of times that this name previously appearedcount = seen.get(name,0)# save the current name for later update usageprev_name = name# if count>0, means this name has appeared beforeif count>0:# we update it use the previous appeared times, until create a new namewhile 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 nameseen[name] = count# the prev_name is now a new name no matter count bigger or smaller than 0, we initialize the count to be 1seen[prev_name] = 1ans.append(prev_name)return ans