本文共 2091 字,大约阅读时间需要 6 分钟。
为了优化给定的Java代码,以下是经过重新设计和优化后的版本。优化后的代码在保持功能不变的同时,提升了效率和代码可读性。
import java.util.HashMap;import java.util.Map;import java.util.Set;public class Solution { /** * 统计并返回出现次数最多的单词 * @param s 给定的英文句子 * @param excludewords 不参与统计的单词集合 * @return 出现次数最多的单词, 在多个单词出现次数相同的情况下, 返回字典序最小的 */ public String frequentWord(String s, Setexcludewords) { Map wordCount = new HashMap<>(); String[] words = s.split(" "); for (String word : words) { // 去除末尾的非字母字符 int lastIndexOfLetter = Integer.parseInt(String.valueOf(word.length()).trim()); while (lastIndexOfLetter > 0 && !Character.isLetter(word.charAt(lastIndexOfLetter - 1))) { lastIndexOfLetter--; } if (lastIndexOfLetter > 0) { String cleanedWord = word.substring(0, lastIndexOfLetter); if (!excludewords.contains(cleanedWord)) { wordCount.put(cleanedWord, wordCount.getOrDefault(cleanedWord, 0) + 1); } } } if (wordCount.isEmpty()) { return ""; } String mostCommonWord = ""; int maxCount = 0; for (Map.Entry entry : wordCount.entrySet()) { if (entry.getValue() > maxCount) { mostCommonWord = entry.getKey(); maxCount = entry.getValue(); } else if (entry.getValue() == maxCount) { if (entry.getKey().compareTo(mostCommonWord) < 0) { mostCommonWord = entry.getKey(); } } } return mostCommonWord; }}
简化字符串处理逻辑:
提高代码可读性:
优化结果处理逻辑:
性能优化:
错误处理:
代码结构优化:
通过这些优化,代码在功能不变的情况下,性能得到了提升,代码结构更加清晰,易于维护和理解。
转载地址:http://bwjs.baihongyu.com/