代码挑战:如果存在重复文件名,请重命名

问题描述 投票:0回答:7

我正在解决在网上找到的编码挑战。 我的第一个测试用例通过了,但第二个测试用例失败了。 我正在尝试确定我失败的第二个测试用例是否是拼写错误。

问题来了:

您将获得一组所需的文件名,按照文件名的顺序排列 创建。由于两个文件不能具有相同的名称,因此出现的文件 之后会以 (k) 的形式对其名称进行补充,其中 k 是 最小的正整数,使得获得的名称不被使用 还没有。

返回将赋予文件的名称数组。

测试用例:

1 - 通过:

  • 输入:
    ["doc", "doc", "image", "doc(1)", "doc"]
  • 输出:
    ["doc", "doc(1)", "image", "doc(1)(1)", "doc(2)"]

2 - 失败:

  • 输入:
    ["a(1)","a(6)","a","a","a","a","a","a","a","a","a","a"]
  • 输出:
    ["a(1)","a(6)","a","a(2)","a(3)","a(4)","a(5)","a(7)","a(8)","a(9)","a(10)","a(11)"]

这是我通过第一个规范的代码:

function fileNaming(names) {
    var finalArr = [],
        obj = {};
    names.forEach(function(val){

        if(obj[val] === undefined){
            if(finalArr.indexOf(val) === -1){
              finalArr.push(val);  
              obj[val] = 0;
            } else {
              obj[val] = 1;
              finalArr.push(val + "(" + obj[val] + ")" );
            }

        } else {
            finalArr.push( val + "(" + (++obj[val]) + ")");
        }
    }); 
    return finalArr;
}

问题:

  • 在第二个测试规范中,为什么没有像有
    "a(1)(1)"
    那样的
    "doc(1)(1)"
    这是拼写错误吗?
  • 如果有人对改进我的方法或替代方法有建议,我将非常感谢您的反馈。
javascript
7个回答
4
投票

这是一个更简单的方法。这个想法是将原始名称和生成的名称都存储在哈希表中:

f = function(xs) {
  
  var c = {}, t = (x, n) => x + "(" + n + ")";
  
  return xs.map(function(x) {
    var n = c[x] || 0;
    
    c[x] = n + 1;

    if(!n)
      return x;
    
    while(c[t(x, n)])
      n++;
    
    c[t(x, n)] = 1;
    return t(x, n);
  });

};


q = ["doc", "doc", "image", "doc(1)", "doc", "doc"];
document.write('<pre>'+JSON.stringify(f(q)));

q = ["a(1)","a(6)","a","a","a","a","a","a","a","a","a","a"]
document.write('<pre>'+JSON.stringify(f(q)));


3
投票

这是我的方法:

def fileNaming(names):
uniq = []
for i in range(len(names)):
    if names[i] not in uniq:
        uniq.append(names[i])
    else:
        k = 1
        while True:
            if (names[i] + "(" + str(k) + ")") in uniq:
                k += 1
            else:
                uniq.append(names[i] + "(" + str(k) + ")")
                break
return uniq

1
投票

使用数组方法

//var arr=["doc", "doc", "image", "doc(1)", "doc"];
 var arr=["a(1)","a(6)","a","a","a","a","a","a","a","a","a","a"];  

 var arr1=new Array();  
    for (var r in arr)
    {
      if(arr1.indexOf(arr[r])>-1)
      {     
        var ind=1;
        while(arr1.indexOf(arr[r]+'('+ind+')')>-1)
        {
        ind++;      
        }
        var str=arr[r]+'('+ind+')';  
        arr1.push(str);
      }
      else
      {
      arr1.push(arr[r]);
      }
    }
    document.write("INPUT:"+arr+"</br>");
    document.write("OUTPUT:"+arr1);

1
投票

这是我的初学者方法:

const renameFiles = arr => {
  const fileObj = {};
  let count = 0;
  const renamed = arr.map(currentFile => {
    if (!Object.keys(fileObj).includes(currentFile)) {
      fileObj[currentFile] = count;
      return currentFile;
    } else {
      count++;
      if (Object.keys(fileObj).includes(`${currentFile}(${count})`)) {
        count++;
        return `${currentFile}(${count})`;
      } else return `${currentFile}(${count})`;
    }
  });
  return renamed;
};


0
投票

这是一个有效的 C++ 实现。

#include <map>
#include <string> 
using namespace std;

string makeName(string n, int i)
{
    string ret = n + "(";
    ret += std::to_string(i);
    ret += ")";
    return ret;
}
std::vector<std::string> fileNaming(std::vector<std::string> names)
{
    map<string, int> lookup;
    vector<string> outNames;
    for (auto name : names)
    {
        auto f = lookup.find(name);
        if (f != lookup.end())
        {
            int index = 1;

            while (lookup.find(makeName(name, index)) != lookup.end())
            {
                index++;
            }
            name = makeName(name, index); // reassign
        }
        lookup[name] = 1;
        outNames.push_back(name);
    }

    return outNames;
}

0
投票

基于已接受答案的JAVA版本:

String[] solution(String[] names) {
    Map<String, Integer> countMap = new HashMap<>();
    String[] result = new String[names.length];
    for (int i = 0; i < names.length; i++) {
        int count = countMap.getOrDefault(names[i], 0);
        countMap.put(names[i], count + 1);
        if (count == 0) { 
            result[i] = names[i];
        } else {
            while (countMap.containsKey(names[i] + "(" + count + ")")) 
                count++;
            countMap.put(names[i] + "(" + count + ")", 1);
            result[i] = names[i] + "(" + count + ")";
        }
    }
    return result;
}

-2
投票

这是我在 Javascript 中的方法:

function fileNaming(names) {
    for (i in names) {
        if (names.slice(0,i).includes(names[i])) {
            j = 1
            while (names.slice(0,i).includes(names[i]+"("+j.toString()+")")) {j++}
            names[i] += "(" + j.toString() + ")"}}
    return names
}
© www.soinside.com 2019 - 2024. All rights reserved.