todo 高盛测试工 电话

两个我不会的bq
客户要看机密文件
同事抢功,不展示你

要强制onsite,没劲……

有个双重loop的优化,我没写出来
链表有没有环

 

/*
 * Click `Run` to execute the snippet below!
 */

import java.io.*;
import java.util.*;

/*
 * Given a large string with multiple words in it.
Example - "I am happy to be a coder and very happy to called as a good coder. Sometimes coding can be fun and some other times a challenge, but as a coder I enjoy every bit of it. I do change streams but they all are milestones of becoming a good coder."
Part 1:  Write code to find the words occurring maximum times in here
          [coder - 4 times, a - 5 times]
Part 2 : Algorithmic complexity of the code?
Part 3: Can we optimize the code?
 */

/**
logic: use hashmap
time:n, space:n
step1: store all the words into the hashmap
step2: compare and get the maximum occurred word
*/

class Solution {
  public static void main(String[] args) {
    String sentence = "I am happy to be a coder and very happy to called as a good coder . Sometimes coding can be fun and some other times a challenge, but as a coder I enjoy every bit of it. I do change streams but they all are milestones of becoming good coder .";
    
    List<String> resultList = new ArrayList<String>();
    System.out.println("maximum occurred word = " + findWord(sentence));
  }
  
  public static List<String> findWord(String sentence) {
    //corner cases
    //output:{'a-4''coder-4'}, use a list to store result
    //sentence == null, "", too long, input some other data types, 1 word
    List<String> resultList = new ArrayList<String>();
    
    //step1: store all the words into the hashmap
    String[] arr = sentence.split(" ");
    HashMap<String, Integer> hs = new HashMap<String, Integer>();
    for (int i = 0; i < arr.length; i++) {
      hs.put(arr[i], hs.getOrDefault(arr[i], 0) + 1);
    }
    
    //step2: compare and get the maximum occurred word
    //create a set to iterate over HashMap
    Set<Map.Entry<String, Integer>> set = hs.entrySet();
    String key = "";
    int value = 0;
    
    for (Map.Entry<String, Integer> map : set) {
      //check and get the highest frequency
      if (map.getValue() > value) {
          value = map.getValue();
          key = map.getKey();
        
      }
    }
    
    
    //after the loop, check again, get which words's freq = maximum freq
    for (Map.Entry<String, Integer> map : set) {
      if (map.getValue() == value) {
          key = map.getKey();
        
        String resString = key + " " + String.valueOf(value);
        resultList.add(resString);
      }
    }
    
    return resultList;
  }
}

 

 
posted @ 2021-10-23 04:41  苗妙苗  阅读(18)  评论(0编辑  收藏  举报