java - 为什么顺序文件命名不起作用?
问题描述
我正在尝试解决这个问题。
问题陈述
您正在开发文件管理器,但遇到了问题。您意识到两个文件不能具有相同的名称,如果发生冲突,则必须在后面的文件附加一个数字N
,该N
数字是该特定文件名未使用的最小正数。该数字以 的形式附加file_name(N)
。编写代码来解决您的问题。您将获得一个文件名字符串数组。您需要假设如果文件名出现在数组中的较早位置,则它是首先创建的。
注意: file_name
和file_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);
}
}
解决方案
如果所有测试都失败,那么很可能是因为您的输出在名字前有一个空格。
输出应该是文件名,以空格分隔,而不是以空格为前缀。
如果您尝试输入
"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)
推荐阅读
- postgresql - Ecto:来自运行时值的动态片段
- linux - 自动化 Azure DevOps Linux 代理
- python-3.x - 用 Python 进行英语测试
- amazon-s3 - 签署具有未来到期和开始日期的 S3 URL
- python-3.x - 如何影响图形节点的位置以进行可视化?
- tensorflow - 如何在 Tensorflow 中使用 GPU 进行大矩阵分解
- git - “退出状态 128”试图从 golang 创建 git 分支
- pandas - 如何对多列中的数据进行分箱?
- swift - 有没有办法在 5 秒后传递一个变量?
- node.js - 解析服务器和 node.js 基础知识入门