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
相关产品推荐
相关产品推荐

