首页 > 解决方案 > 为什么顺序文件命名不起作用?

问题描述

我正在尝试解决这个问题


问题陈述

您正在开发文件管理器,但遇到了问题。您意识到两个文件不能具有相同的名称,如果发生冲突,则必须在后面的文件附加一个数字N,该N数字是该特定文件名未使用的最小正数。该数字以 的形式附加file_name(N)。编写代码来解决您的问题。您将获得一个文件名字符串数组。您需要假设如果文件名出现在数组中的较早位置,则它是首先创建的。 注意: file_namefile_name(2)是两个不同的文件名,即如果一个文件名已经附加了一个数字,则它是一个不同的文件名。

输入 第一行包含N,字符串的数量。下一行包含N空格分隔的字符串(文件名)。

输出 在进行必要的更改后打印文件名,用空格分隔。

约束

1 ≤ N ≤ 50 1 ≤ file_name.length ≤ 25 文件名没有空白字符

样本输入

7
file sample sample file file file(1) file(1)

样本输出

file sample sample(1) file(1) file(2) file(1)(1) file(1)(2)

下面是我的代码。当我用自己的文件名测试它时,它可以很好地重命名,但是当我提交它时,测试失败了。我想知道我的代码有什么问题以及为什么它不起作用。

import java.util.Scanner;

public class Dcoder {
  public static void main (String[] args) {
    Scanner scanner = new Scanner (System.in);

    // Read number of file names and create
    // an array to hold them
    String[] fileNames = new String[scanner.nextInt ()];

    // Fill the array with the supplied names
    // from System.in
    for (int i = 0; i < fileNames.length; i++)
      fileNames [i] = scanner.next ();

    // Modify the file names
    for (String fileName : fileNames) {
      int count = 0;
      for (int i = 0; i < fileNames.length; i++)
        if (fileName.equals (fileNames [i])) {
          fileNames [i] = fileNames [i] + (count == 0 ? "" : "(" + count + ")");
          count++;
        }
    }

    // Print out the modified list of file names
    for (String fileName : fileNames)
      System.out.print (" " + fileName);
  }
}

标签: java

解决方案


  • 如果所有测试都失败,那么很可能是因为您的输出在名字前有一个空格。

    输出应该是文件名,以空格分隔,而不是以空格为前缀

  • 如果您尝试输入"file file(1) file file",您的代码将输出

     file file(1) file(1)(1) file(2)
    

    但正确的输出是

    file file(1) file(2) file(3)
    

为了获得更好的性能,您应该使用Set.

static void printUnique(String... fileNames) {
    Set<String> used = new HashSet<>();
    for (int i = 0; i < fileNames.length; i++) {
        String newName = fileNames[i];
        for (int j = 1; ! used.add(newName); j++)
            newName = fileNames[i] + "(" + j + ")";
        if (i != 0)
            System.out.print(" ");
        System.out.print(newName);
    }
    System.out.println();
}

测试

printUnique("file", "sample", "sample", "file", "file", "file(1)", "file(1)");
printUnique("file", "file(1)", "file", "file");

输出

file sample sample(1) file(1) file(2) file(1)(1) file(1)(2)
file file(1) file(2) file(3)

推荐阅读