分享前几天遇到的一道面试题!

前几天面试遇到的一个问题,哎当时没好好准备,基础也太差(现在也差),想了很久,想出一个答案。
题目:读取文件,获取文件中出现次数最多和最少的字符并显示。

下面给出我的解决办法,你们如果有好想法的话欢迎提出来哦~

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


public class IOtest {
    public static void main(String[] args) throws IOException
    {
        BufferedReader br=new BufferedReader(new FileReader(new File("C:/1.txt")));

        int i=-1;
        StringBuffer sb=new StringBuffer();
        while((i=br.read())!=-1)
        {
            sb.append((char)i);
        }
        String str=sb.toString();
        System.out.println(str);
        HashMap<Character,Integer> maps=getMapByString(str);
        System.out.println("出现次数最多的是:"+getMax(maps));
        System.out.println("出现次数最少的是:"+getMin(maps));
    }

    public static HashMap<Character,Integer> getMapByString(String str)
    {
        HashMap<Character,Integer> maps=new HashMap<Character,Integer>();
        for(int i=0;i<str.length();i++)
        {
            char c=str.charAt(i);
            if(maps.containsKey(c))
            {
                maps.put(c, maps.get(c)+1);
            }
            else
            {
                maps.put(c, new Integer(1));
            }
        }
        return maps;
    }

    public static String getMax(HashMap<Character,Integer> map)
    {
        char maxc = 0;
        int maxcount=0;
        Set set=map.entrySet();
        Iterator<Map.Entry> it=set.iterator();
        while(it.hasNext())
        {
            Map.Entry me=it.next();
            char c=(Character)me.getKey();
            int temp=((Integer)me.getValue());
            if(temp>maxcount)
            {
                maxcount=temp;
                maxc=c;
            }
        }
        return (maxc+":"+maxcount).toString();
    }

    public static String getMin(HashMap<Character,Integer> map)
    {
        char minc=0;
        int mincount=0;
        Set set=map.entrySet();
        Iterator<Map.Entry> it=set.iterator();
        while(it.hasNext())
        {
            Map.Entry me=it.next();
            char c=(Character)me.getKey();
            int temp=(Integer)me.getValue();
            if(mincount==0)
            {
                mincount=temp;
                minc=c;
            }
            else
            {
                if(temp<mincount)
                {
                    mincount=temp;
                    minc=c;
                }
            }

        }
        return (minc+":"+mincount).toString();
    }

}

显示结果:
abbasdawasdsda
出现次数最多的是:a:5
出现次数最少的是:w:1

abbasdawasdsdadsaihfaegfwgyqegfjwhqbfhdmsabaewkygfuyaskudysfhfbewuyafeawwefwqefsdafew
出现次数最多的是:a:13
出现次数最少的是:m:1

“`

猜你喜欢

转载自blog.csdn.net/m0_37942202/article/details/81749018