计算一个字符串不重复字符个数

题目给出的函数原型如下: int getCountOfString(const char *str); 由于参数是const的,所以字符串本身肯定是不能被修改的,题目大致思路就是备份一份字符串到堆空间中(可修改),然后遍历堆空间将重复的字符串置成\0,最后遍历整个堆上的字符串将去除\0后得到的总数返回。

代码语言:javascript
复制
int getCountOfString(const char* str)
{
// 记录返回值
int result = 0;
// 记录字符串个数
int nCount = 0;
const char* strBak = str;
while (*strBak++) nCount++;
// 堆中申请内存
char* strTmp = (char*)malloc(nCount + 1);
// 将字符串拷贝到堆中内存
strcpy(strTmp, str);
// 打印下原来的字符串
printf(“%s\n”, strTmp);
// 循环遍历,从第一个到最后一个一次对比
for (int i = 0; i < nCount - 1; i++)
{
// j = i + 1 意思就是跳过之前对比过的
for (int j = i + 1; j < nCount - 1; j++)
{
// 将相同的字符置成\0
if (strTmp[i] == strTmp[j])
strTmp[j] = ‘\0’;
}
}
// 重新遍历得到去除\0后的总数
for (int i = 0; i < nCount - 1; i++)
{
if (strTmp[i] != ‘\0’)
result++;
}
// 释放堆中内存
free(strTmp);
strTmp = NULL;
return result;
}