首页 > 试题广场 >

简单错误记录

[编程题]简单错误记录
  • 热度指数:83631 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
开发一个简单错误记录功能小模块,能够记录出错的代码所在的文件名称和行号。
处理:
1.记录最多8条错误记录,对相同的错误记录(即文件名称和行号完全匹配)只记录一条,错误计数增加;(文件所在的目录不同,文件名和行号相同也要合并)
2.超过16个字符的文件名称,只记录文件的最后有效16个字符;(如果文件名不同,而只是文件名的后16个字符和行号相同,也不要合并)
3.输入的文件可能带路径,记录文件名称不能带路径

数据范围:输入错误记录数量满足 ,每条记录的长度满足

输入描述:
一行或多行字符串。每行包括带路径文件名称,行号,以空格隔开。
文件路径为windows格式
如:E:\V1R2\product\fpgadrive.c 1325


输出描述:
将所有的记录统计并将结果输出,格式:文件名代码行数数目,一个空格隔开,如: fpgadrive.c 1325 1 
结果根据数目从多到少排序,数目相同的情况下,按照输入第一次出现顺序排序。
如果超过8条记录,则只输出前8条记录.
如果文件名的长度超过16个字符,则只输出后16个字符
示例1

输入

E:\V1R2\product\fpgadrive.c 1325

输出

fpgadrive.c 1325 1
推荐
L0L头像 L0L
//先将所有的字符串存入哈希表,key为字符串,value为<出现顺序,出现次数>,顺序取相同的字符串的最小值,次数一直累加
//排序的话,利用set重写比较器,按次数降序,次数相同则按出现顺序排列
//插入过程利用hash时间复杂度可以认为是O(n)
//排序过程set的是红黑树,可以认为是O(nlgn) ,总的复杂度就是这个了 
#include<iostream>
#include<unordered_map>
#include<set>
#include<string.h>
using namespace std;
struct info{//记录出现的顺序,和次数 
	int rank;
	int count;
	info(int rank,int count){
		this->rank=rank;
		this->count=count;
	}
};
struct fullinfo{//一条完整的结果,字符串和次数 
	string file;
	int rank;
	int count;
	fullinfo(string file,int rank,int count){
		this->file=file;
		this->rank=rank;
		this->count=count;
	}
};
struct classcomp {//set的比较器 
  bool operator()(const struct fullinfo& f1,const struct fullinfo& f2){
		if(f1.count==f2.count)
			return f1.rank<f2.rank;
		return f1.count>f2.count;
	}
};
typedef struct info INFO;
typedef struct fullinfo FULLINFO;
int main(){
	unordered_map<string,INFO> record;
	unordered_map<string,INFO>::iterator it;
	unordered_map<string,INFO>::const_iterator itfind;
	set<FULLINFO,classcomp> ret;
	set<FULLINFO,classcomp>::iterator sit;
	string linestr;//一行输入 
	string file;//文件名+行号 
	int pos;//空格的位置 
	int i=1;
	while(getline(cin,linestr)){
		if(linestr.length()==0)
			break;
		pos=linestr.rfind("\\");
		file=linestr.substr(pos+1);//拆分得到最后的filename和count 
		itfind=record.find(file);//在map中查看是否已经有了该字符串,没有则插入,有则次数加1 
		if(itfind==record.end()){
			INFO tmpi(i,1);
			record.insert(pair<string,INFO>(file,tmpi));
		}
		else{
			INFO tmpi(itfind->second.rank,itfind->second.count+1);
			record.erase(file);
			record.insert(pair<string,INFO>(file,tmpi));
		}
		i++;
	}
	for(it=record.begin();it!=record.end();it++){
		FULLINFO tmpfull(it->first,it->second.rank,it->second.count);//构建排序的set集合 
		ret.insert(tmpfull);
	}
	for(i=0,sit=ret.begin();sit!=ret.end()&&i<8;++sit,++i){//最多输出8条记录,file少于16位 
		if(file.find(" ")<=16){ 
			cout<<(*sit).file<<" "<<(*sit).count<<endl;
			} 
		else{
			cout<<(*sit).file.substr(file.find(" ")-16)<<" "<<(*sit).count<<endl;
		} 
		
	}
	return 0;
} 

编辑于 2015-11-14 14:14:24 回复(28)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static Map<String,Integer> mapID=new HashMap<>();
    // public static Map<String,Integer> mapindex=new HashMap<>();
    public static ArrayList<String> mapindex=new ArrayList<String>();
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String[] get=in.nextLine().split("\\s+");
            String[] getpath=get[0].split("\\\\");
            int rownum=Integer.valueOf(get[1]);
            String filename=getpath[getpath.length-1];//取的文件名
            if(filename.length()>16) filename=filename.substring(filename.length()-16,filename.length());
            String ID=filename+" "+String.valueOf(rownum);
                if(mapID.containsKey(ID)) 
                    mapID.put(ID,mapID.get(ID)+1);
                else {
                    mapID.put(ID,1);
                    mapindex.add(ID);
                }
        }
        if(mapID.isEmpty()){
             System.out.println("fgddfgdfgdfgxf");
        }
        int max=0;
        int maxid=-1;
        boolean[] vis=new boolean[mapindex.size()];
        for(int j=0;j<8;j++){
           for(int z=0;z<mapindex.size();z++){
                if(!vis[z]&&max<mapID.get(mapindex.get(z))){
                    maxid=z;
                    max=mapID.get(mapindex.get(z));
                }
            //System.out.println(mp + " " + mapID.get(mp));
            // System.out.println("key = " + mp + ", value = " + mapID.get(mp));
            } 
            if(maxid>=0){
                vis[maxid]=true;
                System.out.println(mapindex.get(maxid) + " " + mapID.get(mapindex.get(maxid)));
            }
            //复原
            max=0;maxid=-1;
        }
        
    }
}
发表于 2023-05-14 17:52:53 回复(0)
java最简求解方案,一行代码最优化解决字符串匹配
import java.lang.*;
import java.util.*;
import java.util.regex.*;

public class Main{
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        Map<String,Integer> map=new LinkedHashMap<String, Integer>();
        while(sc.hasNext()){
            String content=sc.nextLine();
//            if (content.equals("@"))break;
            Matcher m=Pattern.compile("([^\\\\]{0,16}\\s*\\d*$)").matcher(content);
            m.find();
            if(!map.containsKey(m.group(1))){
                map.put(m.group(1),1);
            }else if (map.containsKey(m.group(1))){
                map.put(m.group(1),map.get(m.group(1))+1);
            }
        }
        List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
        Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o2.getValue()-o1.getValue();//从大到小排序
            }
        });
        int index=0;
        for (Map.Entry<String, Integer> entry : entries) {
            index++;
            System.out.println(entry.getKey()+" "+entry.getValue());
            if(index==8)
                break;
        }
    }
}


发表于 2020-11-04 11:30:12 回复(1)
import java.util.*;

//净文件名和行号完全匹配才算相同的错误,所以把文件名+行号作为key

public class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        Map<String, Integer> map = new LinkedHashMap<>();//保证按照存入顺序
        while (sc.hasNext())
        {
            String path = sc.next();
            int pos = sc.nextInt();
            String[] strings = path.split("\\\\");//以反斜杠分割,记不起来也可以使用replace("\"," ")再用空格分割
//            String[] strings = path.replace("\\", " ").split(" ");
            String filename = strings[strings.length - 1];
//            System.out.println(filename+":"+pos);

            String key = filename + " " + pos;//把全文件名和行数合并为key
            if (!map.containsKey(key))//之后再处理长度超过16的情况
            {
                map.put(key, 1);
            }
            else
            {
                map.put(key, map.get(key) + 1);
            }
        }
        //sort(装满Student对象的list集合, new Comparator<Student>)
        //sort的第一个参数是list集合
        //这里可以sort(装满map的entry对象的list集合, new Comparator<Entry>)
        List<Map.Entry<String, Integer>> list = new LinkedList<>(map.entrySet());//别忘了传入参数
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>()
        {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2)
            {
                return o2.getValue() - o1.getValue();
            }
        });

        //只输出前8条
        for (int i = 0; i < 8; i++)
        {
            String[] split = list.get(i).getKey().split(" ");//list存的是EntrySet,entry的getKey方法获取全文件名+位置,再分割出来全文件名
            if (split[0].length() > 16)
            {
                split[0] = split[0].substring(split[0].length() - 16);
            }
            System.out.println(split[0] + " " + split[1] + " " + list.get(i).getValue());
        }
    }

}

发表于 2020-02-29 12:44:44 回复(0)
彻底搞无语了~,提交运行报错如下,尽管已经加上了“\r\n”
代码如下,欢迎大神指正~
import java.util.Scanner;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Arrays;
public class Main{
    public static void main(String[] args){
        
        Scanner in=new Scanner(System.in);
        int entryCount=0;
        ArrayList<String> infos=new ArrayList<>();
        ArrayList<Integer> counts=new ArrayList<>();
        
        while(in.hasNext()){
            String fullPath=in.next();
            int lineNum=in.nextInt();
            int lastIndex=fullPath.lastIndexOf("\\");
            String info=fullPath.substring(lastIndex+1,fullPath.length())+" "+lineNum;
            int index=infos.indexOf(info);
            
            if(index>=0){
                int data=counts.get(index)+1;
                counts.set(index,data);
            }else{
                infos.add(info);
                counts.add(1);
            }
            entryCount++;
        }
        
        int num=entryCount;
        int printCount=0;
        outer:
            while(num>0){
                int i=counts.indexOf(num);
                while(i>=0){
                    int iSpace=infos.get(i).indexOf(" ");
                    String temp=infos.get(i);
                    if(printCount<7){
                        if(iSpace>16){
                            System.out.print(temp.substring(0,16)+temp.substring(iSpace,temp.length())+" "+counts.get(i)+" ");
                        }else{
                            System.out.print(temp+" "+counts.get(i)+" ");
                        }
                    }else{
                        if(iSpace>16){
                            System.out.println(temp.substring(0,16)+temp.substring(iSpace,temp.length())+" "+counts.get(i)+"\r\n");
                        }else{
                            System.out.println(temp+" "+counts.get(i)+"\r\n");
                        }
                        break outer;
                    }
                    printCount++;
                    infos.remove(i);
                    counts.remove(i);
                    i=counts.indexOf(num);
                }
                num--;
            }

        in.close();
    }
}

发表于 2020-02-12 22:53:55 回复(1)
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Scanner;
public class Main{
    private static class file{
        public String name;//文件位置名
        public int cnt;//文件出现次数
        public file(String a,int b){
            this.name=a;
            this.cnt=b;
        }
    }
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        HashMap<String,Integer> map = new HashMap<String,Integer>();//key:文件名;value:出现次数
        final HashMap<String,Integer> indexMap = new HashMap<String,Integer>();//key:文件名;value:首次出现的位置         
            int count=0;//统计不重复的错误数量
        while(input.hasNext()){
            String s = input.nextLine();
            int begin = s.lastIndexOf('\\');
            String position = s.substring(begin+1,s.length());
            if(map.containsKey(position)){
                int cnt = map.get(position);
                map.put(position, cnt+1);
            }else{
                map.put(position, 1);
                indexMap.put(position, count);
                count++;
            }
        }
        file[] arr = new file[count];
        count=0;
        Iterator<Entry<String,Integer>> iterator = map.entrySet().iterator();
        while(iterator.hasNext()){
            Entry<String, Integer> entry = iterator.next();
            arr[count++] = new file(entry.getKey(),entry.getValue());
        }
        Arrays.sort(arr, new Comparator<file>(){//若出现次数不同,按大到小;若相同按首次输入的顺序 @Override public int compare(file o1, file o2) {
                if(o2.cnt==o1.cnt){
                    return indexMap.get(o1.name)-indexMap.get(o2.name);
                }
                return o2.cnt-o1.cnt;
            }
        });
        count=0;
        for(file f:arr){
            String name = f.name;
            int space = name.lastIndexOf(' ');
            if(space>16) name = name.substring(space-16, name.length());
            System.out.println(name+" "+f.cnt);
            count++;
            if(count==8) break;       }
    }
}

编辑于 2018-08-29 15:57:41 回复(0)
package recruit2016;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Scanner;
import java.util.Set;

public class Practice9
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        LinkedHashMap<String, Integer> map = new LinkedHashMap<String, Integer>();//用LinkedHashMap保证取出顺序等于加入顺序
        while(in.hasNext())
        {
            String sss = in.next();
            int line = in.nextInt();
            String s = sss + " " +String.valueOf(line);
            int index = s.lastIndexOf("\\");
            String str = s.substring(index+1, s.length());//先不管16字符限制,将文件名截取出来
            if(map.get(str) == null)//放到map里,value记录出现次数
            {
                map.put(str, new Integer(1));
            }
            else
            {
                int temp = map.get(str);
                map.put(str, new Integer(temp+1));
            }
        }
        ArrayList<String> list = new ArrayList<String>();//list记录文件名
        int index1 = 0;
        int[] count = new int[map.size()];//count数组记录文件出现次数
        Set<String> set = map.keySet();
        for(String each : set)//从map里拿出来给list和count赋值
        {
            list.add(each);
            count[index1] = map.get(each);
            index1++;
        }
        list = sort(list, count);//按出现次数从大到小冒泡排序,文件名和出现次数同时变化,保证两者一一对应
        for(int i=0; i<(list.size()<8?list.size():8); i++)
        {
            System.out.println(changeStr(list.get(i))+" "+count[i]);
        }
        
    }
    
    public static ArrayList<String> sort(ArrayList<String> list, int[] count)
    {
        for(int i=0; i<count.length; i++)
        {
            for(int j=0; j<count.length-i-1; j++)
            {
                if(count[j] < count[j+1])
                {
                    swap1(count, j);//此处传数组,调用方法里对数组改动,数组变化会体现出来
                    list = swap2(list, j);//同时改变文件名位置
                }
            }
        }
        return list;
    }
    public static void swap1(int[] count, int j)
    {
        int temp =  count[j];
        count[j] = count[j+1];
        count[j+1] = temp;
    }
    public static ArrayList<String> swap2(ArrayList<String> list, int j)
    {
        String temp1 = list.get(j);
        String temp2 = list.get(j+1);
        list.set(j, temp2);
        list.set(j+1, temp1);
        return list;
    }
    public static String changeStr(String str)//实现16字符限制
    {
        int temp = str.indexOf(" ");
        String s = str.substring(0, temp);
        if(s.length() > 16)
        {
            s = s.substring(s.length()-16, s.length());
        }
        return s + str.substring(temp, str.length());
    }
}



发表于 2018-06-09 19:04:47 回复(0)
这题的输入太坑了,居然连多少行都不告诉,不仅如此连个输入结束符都没有,scanner.hasNext()会阻塞等待输入,导致行数不确定时根本无法结束输入进行下一步处理。如果直接回车\n将继续阻塞,下面的代码在牛客上通过测试,在本地根本就是一直阻塞着等待输入,不知道测试用例到底是怎么输入的,坑死了。
    思路:先根据输入一条一条记录下来,相同记录只需要记数加1,输入处理结束后进行一次排序,随后输入小8条记录即可,注意文件名长度不能大于16。
/**
     * Returns true if this scanner has another token in its input.
     * This method may block while waiting for input to scan.
     * The scanner does not advance past any input.
     *
     */
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        getErrorRecords();
    }
    
    static void getErrorRecords() {
        Scanner scanner = new Scanner(System.in);
        ArrayList<Record> arrayList = new ArrayList<>();
        while (scanner.hasNext()) {
            String line = scanner.nextLine();
            //if (line.length() == 0) {
            //    break;
            //}
            String[] strings = line.split(" ");
            String fileName = getFileName(strings[0]);//scanner.next()
            int lineNo = Integer.parseInt(strings[1]);//scanner.nextInt()
            Record record = new Record(fileName, lineNo);
            if (arrayList.contains(record)) {
                Record localRecord = arrayList.get(arrayList.indexOf(record));
//                record.plus1();
                localRecord.plus1();
            } else {
                arrayList.add(record);
            }
//            System.out.println(arrayList);
        }
        //排序
        arrayList.sort(new Comparator<Record>() {
            @Override
            public int compare(Record o1, Record o2) {
                if (o1.errorNum == o2.errorNum) {
                    return 0;
                } else {
                    return o2.errorNum - o1.errorNum;//从大到小
                }
            }
        });
        //输出
        int num = Math.min(8, arrayList.size());
        for (int i = 0; i < num; i++) {
            System.out.println(arrayList.get(i));
        }
    }
    
    static String getFileName(String fullPath) {
        int index = fullPath.lastIndexOf('\\');
        String result = fullPath.substring(index + 1, fullPath.length());
        return result;
    }

    static class Record {
        String fileName;
        int lineNo;
        int errorNum;

        public Record(String fileName, int lineNo) {
            this.fileName = fileName;
            this.lineNo = lineNo;
            this.errorNum = 1;
        }

        public Record(String fileName, int lineNo, int errorNum) {
            this.fileName = fileName;
            this.lineNo = lineNo;
            this.errorNum = errorNum;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj instanceof Record) {
                Record record = (Record) obj;
                return fileName.equals(record.fileName)
                        && lineNo == record.lineNo;
            } else {
                return super.equals(obj);
            }
        }

        public void plus1() {
            this.errorNum++;
        }

        @Override
        public String toString() {
//            return super.toString();
            String trimFileName;
            if (fileName.length() > 16) {
                trimFileName = fileName.substring(fileName.length() - 16);
            } else {
                trimFileName = fileName;
            }
            return trimFileName + " " + lineNo + " " + errorNum;
        }
    }
}

发表于 2018-04-16 17:01:37 回复(0)
//用了笨办法,把所有文件放到map中的同时,放到list中记录先后顺序,然后在排序的时候当
//计数值相同的时候,则取出两者的list下标,下标小的排在前面
import java.util.*;

/**
 * Created by 梅晨 on 2017/9/14.
 */
public class Main {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        HashMap<String,Integer> map = new HashMap<String, Integer>();
        final List<String> set = new ArrayList<String>();
        while (in.hasNext()){
            String[] str = in.nextLine().split("\\\\");
            String file = str[str.length - 1];
            if(!set.contains(file)){
                set.add(file);
            }
            if(!map.containsKey(file)){
                map.put(file,1);
            }else {
                map.put(file,map.get(file) + 1);
            }
        }
        in.close();
        ArrayList<Map.Entry<String,Integer>> list = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                if(o1.getValue() > o2.getValue()){
                    return -1;
                }else if(o1.getValue() < o2.getValue()){
                    return 1;
                }else {
                    int a = 0;
                    int b = 0;
                    for(int i = 0; i < set.size(); i++){
                        if(o1.getKey().equals(set.get(i))){
                            a = i;
                        }
                        if(o2.getKey().equals(set.get(i))){
                            b = i;
                        }
                        
                    }
                    return a < b ? -1 : 1;
                }
            }
        });
        for(int i = 0; i < 8; i++){
            String res = "";
            String[] strs = list.get(i).getKey().split(" ");
            if(strs[0].length() > 16){
                res += strs[0].substring(strs[0].length() - 16,strs[0].length());
            }else {
                res += strs[0];
            }
            res += " " + strs[1] + " " + list.get(i).getValue();
            System.out.println(res);
        }
    }
}


发表于 2017-09-14 01:15:24 回复(0)
package programming;
import java.util.ArrayList;
import java.util.Scanner;

public class ErrorRecord {

public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
ArrayList<String> files = new ArrayList<>();
ArrayList<Integer> rows = new ArrayList<>();
ArrayList<Integer> times = new ArrayList<>();
while (in.hasNext()) {
String f = in.next();// input String
String[] f_name = f.split("\\\\");// split with \
String name = f_name[f_name.length - 1];
int row = in.nextInt();
if (files.contains(name)) {// files在List中不止出现一次!!
boolean flag = true;
for (int i = 0; i < files.size(); i++) {
if (name.equals(files.get(i))) {
if (rows.get(i) == row) {
times.set(i, times.get(i) + 1);
flag = false;
break;
}
}
if (flag) {
files.add(name);
rows.add(row);
times.add(1);
}
} else {
files.add(name);
rows.add(row);
times.add(1);
}
}
in.close();
int max = 0;
for (int ele : times) {
if (ele > max) {
max = ele;
}
}
// output
int out = 0;
for (int i = max; i > 0 && out < 8; i--, out++) {
for (int k = 0; k < times.size(); k++) {
if (times.get(k) == i) {
int len = files.get(k).length();
if ( len > 16) {
System.out.print(files.get(k).substring(len - 16));
} else {
System.out.print(files.get(k));
}
System.out.print(" " + rows.get(k));
System.out.println(" " + times.get(k));
}
}
}
}
}
哪位大神帮忙看下我这个代码,为什么只能通过一个case?
发表于 2017-03-22 12:43:18 回复(0)
  • 很奇怪啊,我的本地输出明明和答案一样,但是在50%的地方卡到了。想不通,代码放上
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in = new Scanner(System.in);

        List<String> input = new ArrayList<String>();
        String input_temp;
        while(in.hasNextLine()){
            input_temp = in.nextLine();
            if(input_temp.equals(""))
                break;
            input.add(input_temp);
        }

        List<String> string_temp = new ArrayList<String>();
        List<Integer> number = new ArrayList<Integer>();
        String result;
        String []temp;
        String []split_temp;
        int index;
        for(int i=0; i < input.size(); i++){
            temp = input.get(i).split(" ");
            split_temp = temp[0].split("\\\\");
            temp[0] = split_temp[split_temp.length-1];
            result = temp[0] + "$" + temp[1];
            if(string_temp.contains(result)){
                index = string_temp.indexOf(result);
                number.set(index, number.get(index)+1);
            }else{
                string_temp.add(result);
                number.add(1);
            }
        }

        for(int i=0; i<string_temp.size(); ++i){
            string_temp.set(i, number.get(i) + "$" + string_temp.get(i));
        }
        number = null;
        //sort the list
        Collections.sort(string_temp, new Comparator<String>() {

            @Override
            public int compare(String o1, String o2) {
                // TODO Auto-generated method stub
                String []compare_string_1 = o1.split("\\$");
                String []compare_string_2 = o2.split("\\$");
                int int_temp_1 = Integer.parseInt(compare_string_1[0]);
                int int_temp_2 = Integer.parseInt(compare_string_2[0]);

                return Integer.compare(int_temp_2, int_temp_1);
            }
        });

        for(int i=0; i<string_temp.size() && i<8; ++i){
            split_temp = string_temp.get(i).split("\\$");
            System.out.println(split_temp[1] + " " + split_temp[2] + " " + split_temp[0]);
        }

        in.close();
    }

}

图片说明

发表于 2017-03-09 15:24:33 回复(0)
import java.util.*;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		Map<String, Integer> map = new LinkedHashMap<>();
		while (sc.hasNextLine()) {
			String s = sc.nextLine();
			if(s == null || "".equals(s)) break;
			String[] split = s.split("\\s");
			String key = split[0].substring(split[0].lastIndexOf('\\') + 1) + " " + split[1];
			map.put(key, map.containsKey(key) ? map.get(key) + 1 : 1);
		}
		List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
		Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
			@Override
			public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
				return o2.getValue().compareTo(o1.getValue());
			}
		});
		for (int i = 0; i < 8; i ++) {
			String[] split = list.get(i).getKey().split("\\s");
			if(split[0].length() > 16) split[0] = split[0].substring(split[0].length() - 16);
			System.out.println(split[0] + " " + split[1] + " " + list.get(i).getValue());
		}
	}
}

编辑于 2017-07-23 22:20:00 回复(4)
下面的代码并没有通过,但在我的IDE上用它给的用例测试没有问题,希望大家帮忙找找哪里不对,多谢!
import java.util.*;
public class Main {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        Map<String, Integer> map = new HashMap<>();
        int max = 1;
        String s, s1, s2;
        String line = null;
        while (in.hasNextLine() && !(line = in.nextLine()).trim().equals("")){
            s = line.substring(line.lastIndexOf('\\') + 1);
            Set<String> keySet = map.keySet();
            if (keySet.contains(s)){
                int value = map.get(s) + 1;
                max = max > value ? max : value; // 判断当前值是否大于max
                map.put(s, value);

            }else {
                map.put(s, 1);
            }
        }
        in.close();
        Set<String> keySet = map.keySet();
        // 输出
        while (max > 0){
            for (String key : keySet){
                if (map.get(key) == max){
                    s1 = key.substring(0, key.indexOf(" "));
                    s2 = key.substring(key.indexOf(" "));
                    if (s1.length() > 16){
                        s1 = s1.substring(s1.length()-16);
                    }
                    System.out.println(s1 + s2 + " " + map.get(key));
                }
            }
            max--;
        }
    }
}

发表于 2017-01-13 12:27:18 回复(0)
import java.util.*;
public class Main{
    public static void main(String[]args){
        Scanner scan=new Scanner(System.in);
        String line="";
        List<String> result=new ArrayList<String>();
        Map<String,Integer>map=new HashMap<String,Integer>();
        while(scan.hasNextLine()){
            line=scan.nextLine();
            int index=line.lastIndexOf("\\");
               line=line.substring(index+1);
               index=line.indexOf(" ");
             String row=line.substring(index);
                row=row.trim();
                line= line.substring(0,index);
                if(line.length()>16){
                    line=line.substring(line.length()-16);
                }
            line=line+" "+row;    
            if(map.containsKey(line)){
                map.put(line, map.get(line)+1);
            }else{
                result.add(line);
                map.put(line, 1);
            }
            
        }   
            for(int i=result.size()-1;i>0;i--){
                for(int j=0;j<i;j++){
                    if(map.get(result.get(j))<map.get(result.get(j+1))){
                        String param=result.get(j);
                        result.set(j,result.get(j+1));
                        result.set(j+1,param);
                    }
                }
            }
            for(int i=0;i<8&&i<result.size();i++){
                System.out.println(result.get(i)+" "+(map.get(result.get(i))));
            }
    }
}
发表于 2016-09-02 12:29:00 回复(3)
package HuaWei;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;


public class HuaWeiErrorRecords {
	


	public static void main(String[] args) {
		
		Scanner in = new Scanner(System.in);
		
		Map<String, Integer> map = new LinkedHashMap<String, Integer>();//LinkedHashMap而不是hashmap!!!!!
		String key;
		String filename;
		String path;
		while(in.hasNext()){
			path = in.next();
			//将路径转换为文件名
			int id = path.lastIndexOf('\\');
			//如果找不到说明只有文件名没有路径
			filename = id<0  ? path : path.substring(id+1); 
			int linenum = in.nextInt();
			//统计频率
			key = filename+" "+linenum;
			if(map.containsKey(key)){
				map.put(key, map.get(key)+1);
			}else{
				map.put(key, 1);
			}
		}
		
		in.close();
		
		//对记录进行排序
		List<Map.Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(map.entrySet());
		Collections.sort(list,new Comparator<Map.Entry<String, Integer>>(){
			//降序
			@Override 
			public int compare(Entry<String, Integer> arg0, Entry<String, Integer> arg1) {
				return(arg1.getValue()-arg0.getValue()) == 0? (arg0.getValue()-arg1.getValue()) : (arg1.getValue()-arg0.getValue());
			}
		});
		//只输出前8条
		int m=0;
		for(Map.Entry<String, Integer> mapping : list){
			m++;
			if(m<=8){
				String[] str = mapping.getKey().split(" ");
				String k = str[0].length()>16 ? str[0].substring(str[0].length()-16) : str[0];
				String n = str[1];
				System.out.println(k+" "+n+" "+mapping.getValue());
			}else{
				break;
			}
			
		}
		
	}

}





发表于 2016-08-27 20:27:42 回复(26)
文件名和行号决定了是否是相同的错误记录,所以可以先把文件名和行号作为一个字符串进行处理。自定义一个fileOutput类,存储文件名和行号这一字符串str,以及错误记录出现的次数count。定义一个ArrayList类型的result用于存储不同的错误记录。
对于每一行输入,分解出文件名和行号字符串str,如果str已经存在于result中,则次数加1,否则创建一个新的记录。得到result即可进行输出。
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
    public static void main(String[] args){
    Scanner scan = new Scanner(System.in);
    ArrayList<fileOutput> result = new ArrayList<fileOutput>();
    Main ww = new Main();
    int t = 0;
    while(scan.hasNextLine()&&t<3){
        t++;
        String str = scan.nextLine();
        String[] s2 = str.trim().split("\\\\");
        String ss = s2[s2.length-1];
        boolean flag = false;
        for(int j=0;j<result.size();j++){
            if(result.get(j).getStr().equals(ss)){
                fileOutput temp = result.get(j);
                temp.setNum(temp.getNum()+1);
                result.set(j, temp);
                flag = true;
                break;
            }
        }
        if(flag == false){
            fileOutput anew = ww.new fileOutput(ss, 1);
            result.add(anew);
        }
    }
    Collections.sort(result, new Comparator<fileOutput>() {
        public int compare(fileOutput o1, fileOutput o2){
        return o2.getNum()-o1.getNum();
        }
    });
    int count = 0;
    while(count<8 && count<result.size()){
        String[] temp = result.get(count).getStr().split(" ");
        String filename = temp[0];
        if(filename.length()>16)
            filename = filename.substring(filename.length() - 16);
        System.out.println(filename+" "+temp[1]+" "+result.get(count).getNum());
        count++;
    }
    scan.close();
}
class fileOutput{
    private String str;
    private int num;
    public fileOutput(String str, int num){
        this.str = str;
        this.num = num;
    }
    public String getStr() {
        return str;
    }
    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }
}
}

编辑于 2016-08-25 17:33:11 回复(1)