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

如何找到字符串中包含不同字符数量最多的单词?

问题解决方法

你当前的代码仅实现了统计输入字符串中单词总数的功能,未覆盖单单词不同字符统计、最大值筛选的核心需求,可按照以下逻辑调整实现:

  • 先将输入的整行字符串按空格分割为单个单词
  • 对每个单词,统计其中不同字符的出现数量
  • 遍历所有单词时同步记录当前不同字符数最多的单词,遍历结束后直接输出即可

可运行参考代码

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

// 统计单个单词的不同字符数量
int countUniqueChars(const string& word) {
    bool existed[256] = {false}; // 覆盖所有ASCII字符范围
    int cnt = 0;
    for (char c : word) {
        if (!existed[(unsigned char)c]) {
            existed[(unsigned char)c] = true;
            cnt++;
        }
    }
    return cnt;
}

int main() {
    string input;
    getline(cin, input);
    stringstream ss(input);
    string word, resWord;
    int maxUnique = 0;

    // stringstream会自动按空格分割单词,可兼容多个连续空格的场景
    while (ss >> word) {
        int curUnique = countUniqueChars(word);
        if (curUnique > maxUnique) {
            maxUnique = curUnique;
            resWord = word;
        }
    }

    cout << resWord << endl;
    return 0;
}

补充说明

如果存在多个单词的不同字符数量完全相同的情况,上述代码会默认返回第一个出现的对应单词;如果需要返回最后一个出现的对应单词,只需要把判断条件curUnique > maxUnique修改为curUnique >= maxUnique即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 10:09:04