思路:
- 给出的文件中提取出<=16个字符长度的文件名
- 放在3维的数组中,判断是否要合并
(但是牛客说此代码存在数组越界等非法访问情况!)
代码:
import java.util.*;
public class Main {
public static void main(String[] args) {
/**
* 输出16个字符,但记录要超过16个
*/
Scanner scanner = new Scanner(System.in);
String string;
int lineNumber, count = 0/*记录计数器*/,resultCount=0/*结果最终条数记录器*/;
boolean merge = false/*当前数据是否合并*/;
List list = new ArrayList();
String[][] result = new String[1000][3];//记录结果用(假设有100条记录)
String[] now = new String[3];//当前用:名字+行数+次数
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 3; j++) {
result[i][j]="0";
}
}
while (scanner.hasNextLine()) {
string = scanner.next();
lineNumber = scanner.nextInt();
int lastIndex = string.lastIndexOf("\\");//得到最右边的文件名
string = string.substring(lastIndex + 1);//拿到文件名
now[0] = string;
now[1] = lineNumber + "";//记录此次输入的值
count++;
for (int i = 0; i < count; i++) {
//合并
if (result[i][0].equals(now[0]) && result[i][1].equals(now[1])) {
int temp = Integer.parseInt(result[i][2]);
temp++;
result[i][2]=temp+"";//计数加一
merge = true;//成功合并
break;
}
}
if (merge == false) {//添加
result[resultCount][0] = now[0];
result[resultCount][1] = now[1];
result[resultCount][2] = "1";
resultCount++;
}
merge=false;
//排序:每次把最大的放在前面。
//修改——要稳定
for (int i = 0; i < resultCount-1; i++) {
for (int j = 0; j < resultCount-i-1; j++) {
if(Integer.parseInt(result[j][2])<Integer.parseInt(result[j+1][2])){
String str0=result[j][0],
str1=result[j][1],
str2=result[j][2];
result[j][0]=result[j+1][0];//交换两个数据
result[j][1]=result[j+1][1];
result[j][2]=result[j+1][2];
result[j+1][0]=str0;
result[j+1][1]=str1;
result[j+1][2]=str2;
}
}
}
int outputCount=8;
if(resultCount<8)
outputCount=resultCount;
for (int i = 0; i < outputCount; i++) {
if(result[i][0].length()>16){
System.out.print(result[i][0].substring((result[i][0].length()-16))+" ");
}
else {
System.out.print(result[i][0]+" ");
}
System.out.print(Integer.parseInt(result[i][1])+" ");
System.out.print(Integer.parseInt(result[i][2]));
System.out.println();
}
}
}
}