gpt4 book ai didi

c - 编写一个 C 程序,删除除最后一个以外的所有出现的字符

转载 作者:行者123 更新时间:2023-12-05 09:07:14 25 4
gpt4 key购买 nike

我正在尝试编写一个 C 程序来删除字符串中除最后一次出现之外的所有重复字符。例如,如果我有字符串

char word[]="Hihxiivaeiavigru";

输出应该是:

printf("%s",word);
hxeavigru

我目前拥有的:

#include <stdio.h>
#include <string.h>

int main()
{
char word[]="Hihxiiveiaigru";

for (int i=0;i<strlen(word);i++){
if (word[i+1]==word[i]);
memmove(&word[i], &word[i + 1], strlen(word) - i);
}

printf("%s",word);
return 0;
}

我不确定我做错了什么。

最佳答案

对于短字符串,任何算法都可以。 OP 的尝试是 O(n*n)(以及其他工作答案和 @David C. Rankin 确定了 OP 的缺点。)

但是如果字符串的长度是几千、几百万呢?

考虑以下算法:@paulsm4

   Form a `bool` array used[CHAR_MAX - CHAR_MIN + 1] and set each false.

i,unique = n - 1;
From the end of the string (n-1 to 0) to the front:
if (character never seen yet) { // used[] look-up
array[unique] = array[i];
unique--;
}
Mark used[array[i]] as true (index from CHAR_MIN)
i--;
Shift the string "to the left" (unique - i) places

解是O(n)


编码目标太有趣了,不能只发布一个完整编码的答案。

关于c - 编写一个 C 程序,删除除最后一个以外的所有出现的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65261350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com