T1数组异或操作
签到题,直接翻译
class Solution {
public:
int xorOperation(int n, int start) {
vector<int> nums;
int ans;
for(int i = 0; i < n; i++)
nums.push_back(start + 2*i);
ans = nums[0];
for(int i = 1; i < n; i++)
ans ^= nums[i];
return ans;
}
};
T2保证文件名唯一
题目大意:给定一组字符串,为每个相同的字符串附加累加的序号以保证字符串名称唯一。
这道题的重点就在于“判断某字符串是第几次出现”,显然是一道字符串hash。
用一个map来记录某字符串出现的次数,再用一个集合来判断当前字符串是否出现就可以了。
class Solution {
public:
vector<string> getFolderNames (vector<string> &names) {
unordered_set<string> s;
unordered_map<string, int> cnt;
vector<string> ans;
s.clear ();
cnt.clear ();
for (auto i : names)
{
if (s.count(i))
{
if (cnt.count(i) == 0)
cnt[i] = 1;
while (s.count(i + "(" + to_string(cnt[i]) + ")"))
cnt[i]++;
string str = i + "(" + to_string(cnt[i]) + ")";
ans.push_back(str);
s.insert(str);
cnt[i]++;
}
else
{
s.insert(i);
ans.push_back(i);
}
}
return ans;
}
};