1487. Making File Names Unique
https://leetcode.com/problems/making-file-names-unique/
Given an array of strings names
of size n
. You will create n
folders in your file system such that, at the ith
minute, you will create a folder with the name names[i]
.
Since two files cannot have the same name, if you enter a folder name which is previously used, the system will have a suffix addition to its name in the form of (k)
, where, k
is the smallest positive integer such that the obtained name remains unique.
Return an array of strings of length n
where ans[i]
is the actual name the system will assign to the ith
folder when you create it.
Example 1:
Input: names = ["pes","fifa","gta","pes(2019)"]
Output: ["pes","fifa","gta","pes(2019)"]
Explanation: Let's see how the file system creates folder names:
"pes" --> not assigned before, remains "pes"
"fifa" --> not assigned before, remains "fifa"
"gta" --> not assigned before, remains "gta"
"pes(2019)" --> not assigned before, remains "pes(2019)"
Example 2:
Input: names = ["gta","gta(1)","gta","avalon"]
Output: ["gta","gta(1)","gta(2)","avalon"]
Explanation: Let's see how the file system creates folder names:
"gta" --> not assigned before, remains "gta"
"gta(1)" --> not assigned before, remains "gta(1)"
"gta" --> the name is reserved, system adds (k), since "gta(1)" is also reserved, systems put k = 2. it becomes "gta(2)"
"avalon" --> not assigned before, remains "avalon"
Example 3:
Input: names = ["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece"]
Output: ["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece(4)"]
Explanation: When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4)".
Example 4:
Input: names = ["wano","wano","wano","wano"]
Output: ["wano","wano(1)","wano(2)","wano(3)"]
Explanation: Just increase the value of k each time you create folder "wano".
Example 5:
Input: names = ["kaido","kaido(1)","kaido","kaido(1)"]
Output: ["kaido","kaido(1)","kaido(2)","kaido(1)(1)"]
Explanation: Please note that system adds the suffix (k) to current name even it contained the same suffix before.
Constraints:
1 <= names.length <= 5 * 10^4
1 <= names[i].length <= 20
names[i]
consists of lower case English letters, digits and/or round brackets.
一系列string表示名字,依次对其中已经在前面出现过的重命名:对每个名字维持counter,将最小的没出现过的count作为(count)后缀加在名字后。统计名字出现的次数用dict,并当遇到a(1)这样的名字并出现在a前时,为了防止a和a(1)在dict中出现计数混淆,用另一个set额外记录所有出现过的名来判断a是否是第一次出现。
import re
class Solution:
def getFolderNames(self, names: List[str]) -> List[str]:
m, res, s = dict(), [], set()
RE = re.compile(r'^(.*)\(([0-9])\)$')
for name in names:
mo = RE.match(name)
if mo is not None:
pre = mo.group(1)
ind = mo.group(2)
if pre not in m:
m[pre] = [set(), 1]
m[pre][0].add(int(ind))
if name in s:
ind = m[name][1]
while ind in m[name][0]:
ind += 1
m[name][0].add(ind)
m[name][1] += 1
name += '(' + str(ind) + ')'
if name not in m:
m[name] = [set(), 1]
s.add(name)
res.append(name)
return res
Last updated
Was this helpful?