You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin集合函数实现:找出仅在单个单词中缺失的字符

问题:找出仅在一个单词中缺失的字符(一行代码实现)

任务说明

  • 核心要求:使用集合函数实现,一行代码完成逻辑
  • 输入:一行由空格分隔的多个单词,示例输入:"abс acb ab"
  • 输出:仅在一个单词中缺失的字符,示例输出:"c"(c仅在最后一个单词ab中缺失)

当前代码与困惑

已编写代码:

fun main() {
    val s = readLine()?.split(" ")?.associateWith { it.map { it } }.also { println(it) }
}

目前仅能将单词拆分为字符列表,不清楚如何通过集合比较实现需求,认为当前思路正确,若有误请提供可行方案。

可行实现方案

你的当前思路偏了,associateWith的映射操作对统计缺失字符没有帮助,我们需要聚焦于字符的存在性统计。以下是符合要求的一行代码实现:

fun main() = readLine()?.split(" ")?.run { flatMap { it.toSet() }.toSet().first { c -> count { c !in it } == 1 } }?.let(::println)

代码逻辑解析

  1. split(" "):将输入字符串拆分为单词列表
  2. flatMap { it.toSet() }.toSet():提取所有出现过的唯一字符,得到字符全集
  3. first { c -> count { c !in it } == 1 }:遍历每个字符,统计有多少个单词不包含该字符,筛选出仅在1个单词中缺失的字符
  4. let(::println):输出最终结果

如果需要更易读的拆分版(核心逻辑仍为一行):

fun main() {
    readLine()?.split(" ")?.let { words ->
        val allChars = words.flatMap { it.toSet() }.toSet()
        val missingOnceChar = allChars.first { char -> words.count { char !in it } == 1 }
        println(missingOnceChar)
    }
}

内容的提问来源于stack exchange,提问作者dieforreborn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 17:02:25