zoukankan      html  css  js  c++  java
  • 计算出一段英文中出现频率最高的单词(第一次面试时没做出来,现在都记忆深刻)

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.InputStreamReader;
    import java.util.HashMap;
    import java.util.Map;
    
    public class StringSum {
        
        /**
         * 统计一段英文中出现次数最多的单词
         * @param filePath 文件的路径
         * @throws Exception 
         */
        public static void stringSumMethod(String filePath) throws Exception{
            File file=new File(filePath);
            FileInputStream input=new FileInputStream(file);
            BufferedReader bf=new BufferedReader(new InputStreamReader(input));
            StringBuffer sb=new StringBuffer();
            String content="";
            while((content=bf.readLine())!=null){
                sb.append(content);
            }
            
            bf.close();
            input.close();
            //System.out.println(sb.toString());
            
            String[] contents=sb.toString().split(" ");
            //System.out.println(contents.length);
            Map<String,Integer> map=new HashMap<String, Integer>();
            
            for(int i=0;i<contents.length;i++){
                //System.out.println(contents[i]);
                if(contents[i].equals("0")) continue;
                
                int times=1;
                for(int j=0;j<contents.length;j++){
                    if(contents[j].equals("0")) continue;
                    if(i==j) continue;
                    if(contents[i].equals(contents[j])){
                        times++;
                        contents[j]="0";//出现重复的就将重复的字符置"0"
                    }
                    //System.out.println(contents[i]+":"+times+"当前次数:"+j);
                }
                //System.out.println(contents[i]+":"+times+"当前次数:"+i);
                map.put(contents[i],times);    
                
            }
    //        System.out.println(map.size());
            //System.out.println(map.toString());
    
            
            int maxValue=0;
            String maxKey="";
            
            for (Map.Entry<String, Integer> entry : map.entrySet()) {
                  // System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
                  if(entry.getValue()>maxValue){
                      maxValue=entry.getValue();
                      maxKey=entry.getKey();
                  }
            }
            System.out.println("出现最多的字符串:"+maxKey+" 出现次数:"+maxValue);
        }
    
    }
  • 相关阅读:
    穷举
    菱形
    6.824 Lab 3: Fault-tolerant Key/Value Service 3A
    6.824 Lab 2: Raft 2C
    6.824 Lab 2: Raft 2B
    一文学会Rust?
    字符串相似度匹配
    解决gson解析long自动转为科学计数的问题
    commonJs requirejs amd 之间的关系
    关于package.json的理解
  • 原文地址:https://www.cnblogs.com/LvLoveYuForever/p/5466951.html
Copyright © 2011-2022 走看看