GuilinDev

Lc1487

05 August 2008

1487 Making File Names Unique

类似Windows中的文件系统,给文件分配名字,有重复的就同样名字后面括号+序号

LinkedHashMap + 递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
    public String[] getFolderNames(String[] names) {
        Map<String, Integer> map = new LinkedHashMap<>(names.length);
        for (String name : names) {
            if (!map.containsKey(name)) {
                map.put(name, 1);
                continue;
            }
            Integer flag = map.get(name);
            ifHasName(map, name, flag);
        }
        return map.keySet().toArray(new String[0]);
    }

    private void ifHasName(Map<String, Integer> map, String name, int flag) {
        String newName = name + "(" + flag + ")";
        if (!map.containsKey(newName)) {
            map.put(name, flag + 1);
            map.put(newName, 1);
            return;
        }
        ifHasName(map, name, flag + 1);
    }
}