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

返回字符串中单次出现大写字母的C++函数错误排查求助

代码问题分析

  • 核心逻辑错误
    排序后相同字符会连续排列,原代码仅判断当前字符与下一个字符不同就直接返回,没有考虑当前字符可能是重复段的最后一个字符。以你给出的输入"ala"为例:
    1. 转大写后得到"ALA",排序后结果为"AAL"
    2. 循环到i=1时,str[1] = 'A',str[2] = 'L'满足不等条件,直接返回了重复字符'A',而非仅出现一次的'L'
  • 边界情况遗漏:如果字符串中所有字符都出现多次,函数走完循环后没有任何返回值,会触发未定义行为。
  • 头文件缺失:代码中使用了cout但没有包含<iostream>头文件,部分编译器会编译失败。

修正方案

修正后逻辑为:排序后遍历字符串,统计每个连续相同字符的出现次数,找到第一个出现次数为1的字符就返回,遍历完无符合要求的字符则返回默认空字符。

#include <algorithm>
#include <string>
#include <iostream>

using namespace std;

char singleOccurrence(string str) {
    transform(str.begin(), str.end(), str.begin(), ::toupper);
    sort(str.begin(), str.end());
    int n = str.length();
    for(int i = 0; i < n; ) {
        int cnt = 1;
        // 统计当前连续相同字符的数量
        while(i + cnt < n && str[i] == str[i + cnt]) {
            cnt++;
        }
        if(cnt == 1) {
            return str[i];
        }
        i += cnt;
    }
    // 所有字符都重复时返回空字符,可根据业务需求调整返回值
    return '\0';
}

int main()
{
   string str = "ala";
   cout << singleOccurrence(str);
   return 0;
}

上述代码输入"ala"会正确输出仅出现一次的字符L。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 09:15:07