数组异或操作
保证文件名唯一 注意这个示例:
C++实现
class Solution { public: int xorOperation(int n, int start) { int res = start; for (int i = 1; i < n;i++) { start += 2; res = res ^ start; } return res; } }; 保证文件名唯一 Java实现 class Solution { public String[] getFolderNames(String[] names) { int len = names.length; // 特殊情况处理 if (len == 0) { return null; } // 初始化结果集字符串 String[] res = new String[len]; // Map<String,Integer> map = new HashMap<>(); for (int i = 0; i < len; i++) { // 如果此前没出现过当前字符串,则直接赋值即可 if (!map.containsKey(names[i])) { res[i] = names[i]; map.put(names[i],1); } else { // 如果出现过,先取出之前出现的次数,再继续判断后面的序号是否出现过 int num = map.get(names[i]); while (map.containsKey(names[i] + "(" + num + ")")) { num++; } // 找到了,直接赋值 res[i] = names[i] + "(" + num + ")"; // 记得更新map map.put(names[i] + "(" + num + ")",1); map.put(names[i],map.get(names[i]) + 1); } } return res; } }C++实现:思路一致的,未加注释
class Solution { public: vector<string> getFolderNames(vector<string>& names) { int n = names.size(); unordered_map<string, int> M; vector<string> res; for(int i = 0; i < n; i++){ string tmp = ""; if(M.find(names[i]) == M.end()){ M[names[i]] = 1; tmp = names[i]; }else{ int k = M[names[i]]; tmp = names[i] + '(' + to_string(k) + ')'; while(M.find(tmp) != M.end()){ k++; tmp = names[i] + '(' + to_string(k) + ')'; } M[names[i]] = k+1; M[tmp] = 1; } res.push_back(tmp); } return res; } };