Making File Names Unique LeetCode solution in Java

1
class Solution {
2
Map<String, Integer> map = new HashMap<>();
3

4
public String[] getFolderNames(String[] names) {
5
String[] op = new String[names.length];
6
int i = 0;
7

8
for (String cur : names) {
9
if (map.containsKey(cur)) {
10
cur = generateCopyName(cur);
11
op[i++] = cur;
12
// System.out.println(map.toString());
13
continue;
14
}
15

16
op[i++] = cur;
17
map.put(cur, 0);
18
// System.out.println(map.toString());
19
}
20

21
return op;
22
}
23

24
private String generateCopyName(String s) {
25
int count = map.get(s) + 1;
26

27
String postfix = "(" + count + ")";
28
StringBuilder sb = new StringBuilder(s);
29
sb.append(postfix);
30

31
boolean isChanged = false;
32
while (map.containsKey(sb.toString())) {
33
sb = new StringBuilder(s);
34
sb.append("(" + count + ")");
35
count++;
36
isChanged = true;
37
}
38
String res = sb.toString();
39
// System.out.println(res);
40

41
if (isChanged) count = count - 1;
42

43
map.put(s, count);
44
map.put(res, 0);
45

46
return res;
47
}
48
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0