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

C语言编写字符串重复字符识别函数无法正常运行求助

问题排查

你的代码存在以下三处核心错误:

  • 返回值r的赋值逻辑错误:每次外层循环都会覆盖r的值,最终返回的仅为字符串最后一个字符的检查结果。例如字符串aab,检查前两个字符时r会被设为0,但检查最后一个无重复的字符b时r会被重置为1,最终返回错误结果。
  • 返回值未初始化:如果传入空字符串,循环不会执行,函数会返回随机的垃圾值,结果不可控。
  • 性能冗余:每次循环都调用strlen()计算字符串长度,该函数需要遍历整个字符串到结束符才返回结果,会增加不必要的开销;且找到重复字符后无需继续遍历,可以直接返回结果。

修复后代码

#include <string.h>

int checkrow(char* row) {
    // 提前计算字符串长度,避免循环中重复计算
    int str_len = strlen(row);
    // 初始默认无重复,返回值为1
    int res = 1;
    for(int i = 0; i < str_len; i++) {
        for(int j = i + 1; j < str_len; j++) {
            if(row[i] == row[j]) {
                // 找到重复直接返回0,无需后续遍历
                return 0;
            }
        }
    }
    return res;
}

优化方案(可选)

如果需要处理长字符串,可改用计数法将时间复杂度从O(n²)降到O(n):

#include <string.h>

int checkrow(char* row) {
    int str_len = strlen(row);
    // 假设字符为ASCII范围,用数组记录每个字符是否出现过
    int char_exist[128] = {0};
    for(int i = 0; i < str_len; i++) {
        unsigned char c = (unsigned char)row[i];
        if(char_exist[c]) {
            return 0;
        }
        char_exist[c] = 1;
    }
    return 1;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 00:24:05