标签:map coder String sentence maximum times 高盛 测试 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; } }
标签:map,coder,String,sentence,maximum,times,高盛,测试,todo 来源: https://www.cnblogs.com/immiao0319/p/15441224.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。