Making File Names Unique LeetCode solution in C++

1
class Solution {
2
public:
3
vector<string> getFolderNames(vector<string> &names) {
4
// You can understand the code by seeing explanation below
5

6
unordered_map<string, int> mp;
7
vector<string> res;
8

9
for (auto i : names) {
10
string val = i;
11
int cnt = mp[val];
12

13
while (mp[val] != 0) {
14
val = i + '(' + to_string(cnt) + ')';
15
cnt++;
16
mp[i] = cnt;
17
}
18
mp[val]++;
19
res.emplace_back(val);
20
}
21
return res;
22

23
// For better Understanding Code explained Line by line
24

25
// names = ["d", "d(1)", "d(2)", "d"]
26

27
// running for loop
28
// val = "d";
29
// cnt = mp[val] = mp["d"] = 0;
30
// mp[val] = 0, so while loop not executed
31
// mp[val]++ -> mp["d"] = 0+1 = 1;
32
// res = ["d"]
33

34
// Same for "d(1)"
35
// mp["d(1)"] = 0+1 = 1;
36
// res = ["d", "d(1)"]
37

38
// Same for "d(2)"
39
// mp["d(2)"] = 0+1 = 1;
40
// res = ["d", "d(1)", "d(2)"]
41

42
// now, i = "d", val = "d";
43
// cnt = mp[val] = mp["d"] = 1, (appeared before)
44
// while loop executed bcoz mp[val] = 1 which is greater than 0
45
// In while loop,
46
// cnt = 1+1 = 2;
47
// val = i + '(' + to_string(cnt) + ')' = "d(2)"
48
// mp[i] = mp["d"] = cnt = 2;
49

50
// now mp[val] = mp["d(2)"] = 1, (appeared before)
51
// while loop executed bcoz mp[val] = 1 which is greater than 0
52
// In while loop,
53
// cnt = 2+1 = 3;
54
// val = i + '(' + to_string(cnt) + ')' = "d(3)"
55
// mp[i] = mp["d"] = cnt = 3;
56

57
// now mp[val] = mp["d(3)"] = 0
58
// while loop closed
59
// mp[val]++ = mp["d(3)"] = 0+1 = 1;
60
// res = ["d", "d(1)", "d(2)", "d(3)"]
61

62
// now, return res;
63
}
64
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0