news 2026/6/10 22:45:52

算法题 两句话中的不常见单词

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
算法题 两句话中的不常见单词

两句话中的不常见单词

问题描述

句子是一串由空格分隔的单词。给定两个句子s1s2,返回所有不常见单词的列表

不常见单词:在两个句子中总共只出现一次,且至少出现在一个句子中的单词。

可以按任意顺序返回答案。

示例

输入:s1="this apple is sweet",s2="this apple is sour"输出:["sweet","sour"]输入:s1="apple apple",s2="banana"输出:["banana"]

算法思路

哈希表统计频次

  1. 核心思想
    • 将两个句子合并,统计每个单词的出现频次
    • 出现频次为 1 的单词就是不常见单词

代码实现

方法一:哈希表统计

importjava.util.*;classSolution{/** * 找出两句话中的不常见单词 * * @param s1 第一个句子 * @param s2 第二个句子 * @return 所有不常见单词的列表 * * 算法思路: * 1. 将两个句子合并统计单词频次 * 2. 频次为1的单词即为不常见单词 */publicString[]uncommonFromSentences(Strings1,Strings2){// 使用哈希表统计单词频次Map<String,Integer>wordCount=newHashMap<>();// 处理第一个句子String[]words1=s1.split(" ");for(Stringword:words1){wordCount.put(word,wordCount.getOrDefault(word,0)+1);}// 处理第二个句子String[]words2=s2.split(" ");for(Stringword:words2){wordCount.put(word,wordCount.getOrDefault(word,0)+1);}// 收集频次为1的单词List<String>result=newArrayList<>();for(Map.Entry<String,Integer>entry:wordCount.entrySet()){if(entry.getValue()==1){result.add(entry.getKey());}}// 转换为数组返回returnresult.toArray(newString[0]);}}

方法二:使用Stream

importjava.util.*;importjava.util.stream.*;classSolution{/** * 使用Stream */publicString[]uncommonFromSentences(Strings1,Strings2){// 合并两个句子的所有单词String[]allWords=(s1+" "+s2).split(" ");// 统计频次并过滤频次为1的单词Map<String,Long>wordCount=Arrays.stream(allWords).collect(Collectors.groupingBy(word->word,Collectors.counting()));// 返回频次为1的单词数组returnwordCount.entrySet().stream().filter(entry->entry.getValue()==1).map(Map.Entry::getKey).toArray(String[]::new);}}

算法分析

  • 时间复杂度:O(m + n)

    • m 和 n 分别是两个句子的长度
    • 分割字符串:O(m + n)
    • 哈希表操作:每个单词 O(1),总共 O(m + n)
    • 构建结果:O(k),其中 k 是不同单词的数量
  • 空间复杂度:O(m + n)

    • 哈希表存储所有不同单词:O(m + n)
    • 结果数组:O(k) ≤ O(m + n)

算法过程

1:s1 = “this apple is sweet”, s2 = “this apple is sour”

单词统计

s1单词: ["this", "apple", "is", "sweet"] s2单词: ["this", "apple", "is", "sour"] 哈希表统计: - "this": 2 - "apple": 2 - "is": 2 - "sweet": 1 - "sour": 1 频次为1的单词: ["sweet", "sour"]

2:s1 = “apple apple”, s2 = “banana”

单词统计

s1单词: ["apple", "apple"] s2单词: ["banana"] 哈希表统计: - "apple": 2 - "banana": 1 频次为1的单词: ["banana"]

3:s1 = “abcd def abcd”, s2 = “def mnop mnop”

单词统计

哈希表统计: - "abcd": 2 - "def": 2 - "mnop": 2 频次为1的单词: [] (空数组)

测试用例

importjava.util.*;publicclassTest{publicstaticvoidmain(String[]args){Solutionsolution=newSolution();// 测试用例1:标准示例Strings1_1="this apple is sweet";Strings2_1="this apple is sour";String[]result1=solution.uncommonFromSentences(s1_1,s2_1);System.out.println("Test 1: "+Arrays.toString(result1));// [sweet, sour]// 测试用例2:重复单词Strings1_2="apple apple";Strings2_2="banana";String[]result2=solution.uncommonFromSentences(s1_2,s2_2);System.out.println("Test 2: "+Arrays.toString(result2));// [banana]// 测试用例3:无结果Strings1_3="abcd def abcd";Strings2_3="def mnop mnop";String[]result3=solution.uncommonFromSentences(s1_3,s2_3);System.out.println("Test 3: "+Arrays.toString(result3));// []// 测试用例4:单个单词Strings1_4="hello";Strings2_4="world";String[]result4=solution.uncommonFromSentences(s1_4,s2_4);System.out.println("Test 4: "+Arrays.toString(result4));// [hello, world]// 测试用例5:一个句子为空Strings1_5="";Strings2_5="hello world";String[]result5=solution.uncommonFromSentences(s1_5,s2_5);System.out.println("Test 5: "+Arrays.toString(result5));// [hello, world]// 测试用例6:两个句子相同Strings1_6="same words here";Strings2_6="same words here";String[]result6=solution.uncommonFromSentences(s1_6,s2_6);System.out.println("Test 6: "+Arrays.toString(result6));// []// 测试用例7:包含数字和特殊字符Strings1_7="hello123 world!";Strings2_7="hello123 test";String[]result7=solution.uncommonFromSentences(s1_7,s2_7);System.out.println("Test 7: "+Arrays.toString(result7));// [world!, test]// 测试用例8:大量重复Strings1_8="a a a a a";Strings2_8="b b b b b";String[]result8=solution.uncommonFromSentences(s1_8,s2_8);System.out.println("Test 8: "+Arrays.toString(result8));// []// 测试用例9:一个单词在两个句子中各出现一次Strings1_9="unique";Strings2_9="unique";String[]result9=solution.uncommonFromSentences(s1_9,s2_9);System.out.println("Test 9: "+Arrays.toString(result9));// []// 测试用例10:混合大小写Strings1_10="Hello hello";Strings2_10="WORLD world";String[]result10=solution.uncommonFromSentences(s1_10,s2_10);System.out.println("Test 10: "+Arrays.toString(result10));// [Hello, hello, WORLD, world]}}

关键点

  1. 问题

    • 不常见单词 = 在两个句子中总共出现1次
    • 不是"在各自句子中只出现1次",而是"在合并后只出现1次"
  2. 字符串分割

    • 使用split(" ")处理空格分隔

常见问题

  1. 为什么不用Set?
    • Set只能判断存在性,无法统计频次
    • 需要知道单词出现了多少次,而不仅仅是是否出现
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/10 14:12:12

技术面试突围:从算法思维到代码质量的系统提升策略

技术面试突围&#xff1a;从算法思维到代码质量的系统提升策略 【免费下载链接】CodingInterviews 剑指Offer——名企面试官精讲典型编程题 项目地址: https://gitcode.com/gh_mirrors/co/CodingInterviews 在竞争激烈的技术面试中&#xff0c;优秀的开发者往往因为一些…

作者头像 李华
网站建设 2026/6/10 16:56:17

Vugu实战指南:7步掌握Go语言WebAssembly开发新范式

Vugu实战指南&#xff1a;7步掌握Go语言WebAssembly开发新范式 【免费下载链接】vugu Vugu: A modern UI library for GoWebAssembly (experimental) 项目地址: https://gitcode.com/gh_mirrors/vu/vugu Vugu是一个创新的现代化UI库&#xff0c;专为Go语言和WebAssembly…

作者头像 李华
网站建设 2026/6/10 16:02:58

5分钟上手Hexo主题Solitude:打造优雅简约的个人博客空间

5分钟上手Hexo主题Solitude&#xff1a;打造优雅简约的个人博客空间 【免费下载链接】hexo-theme-solitude 一个优雅的Heo风格的Hexo主题&#xff0c;接近Heo&#xff0c;完整度高。 项目地址: https://gitcode.com/gh_mirrors/hexo/hexo-theme-solitude 还在为博客主题…

作者头像 李华
网站建设 2026/6/10 14:11:34

WeKnora实战部署:从零搭建智能文档问答系统

WeKnora实战部署&#xff1a;从零搭建智能文档问答系统 【免费下载链接】WeKnora LLM-powered framework for deep document understanding, semantic retrieval, and context-aware answers using RAG paradigm. 项目地址: https://gitcode.com/GitHub_Trending/we/WeKnora …

作者头像 李华
网站建设 2026/6/10 9:46:39

专业B站视频下载工具完整使用手册

专业B站视频下载工具完整使用手册 【免费下载链接】bilidown 哔哩哔哩视频解析下载工具&#xff0c;支持 8K 视频、Hi-Res 音频、杜比视界下载、批量解析&#xff0c;可扫码登录&#xff0c;常驻托盘。 项目地址: https://gitcode.com/gh_mirrors/bilid/bilidown 还在为…

作者头像 李华
网站建设 2026/6/10 19:14:23

如何评估TensorFlow-v2.9镜像的计算性能与显存占用

如何评估 TensorFlow-v2.9 镜像的计算性能与显存占用 在深度学习项目从实验走向落地的过程中&#xff0c;一个稳定、高效的运行环境往往决定了整个开发流程的成败。尽管模型架构和数据质量备受关注&#xff0c;但底层框架的性能表现——尤其是容器化镜像在真实硬件上的计算效率…

作者头像 李华