博客
关于我
【Lintcode】1484. The Most Frequent Word
阅读量:200 次
发布时间:2019-02-28

本文共 2049 字,大约阅读时间需要 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, Set
excludewords) { 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/

    你可能感兴趣的文章
    Python--抽象类接口类
    查看>>
    PYTHON--欧拉习题二
    查看>>
    python--高级应用总结
    查看>>
    python-520表白代码,我看谁说程序员不懂浪漫,送你几套表白代码,一步到位
    查看>>
    Python-Asyncio TypeError:无法在‘;等待‘;表达式中使用对象DICT
    查看>>
    Python-AttributeError:‘;dict&39;对象没有属性‘;序列‘;
    查看>>
    Python-ldap:是否可以在不显式写入密码的情况下进行绑定?
    查看>>
    python出现 unknown encoding: idna 的处理方法
    查看>>
    Python出现 RuntimeError: dictionary changed size during iteration 的解决方法
    查看>>
    Python-numpy(2)数组的操作
    查看>>
    Python-Numpy的tile函数用法
    查看>>
    python-open函数
    查看>>
    Python-Pandas-将特定函数应用于给定级别-多索引数据框架
    查看>>
    python-queue队列通信
    查看>>
    python-ros No module named PyKDL
    查看>>
    python-social-auth 是否需要会话
    查看>>
    Python再获年度编程语言,微软或成最大赢家
    查看>>
    python-week5
    查看>>
    Python写表情包搜索工具(非常详细)零基础入门到精通,收藏这一篇就够了
    查看>>
    Python-【1】配置
    查看>>