用于从给定字符串中删除重复字符的C程序。它使用O(n2)我们可以按O(n)顺序进行。请对此计划发表评论。
int main()
{
char a[100],b[100],temp='\0';
int i,n,j,count=0,p=0,k=0;
printf("ENTRE THE STRING \n");
scanf("%s",a);
n = strlen(a);
i=0;
while(i < n)
{
count=0;
temp = a[i];
for(j = i ; j < n ; j++ )
{
if(temp==a[j])
{
count++;
}
}
if(count<2)
{
b[k] = temp;
k++;
}
i++;
}
b[k]='\0';
printf("THE RESULTED STRING IS \n");
for(p = 0 ; p < k ; p++)
printf("%c ",b[p]);
printf("\n");
return 0;
}
答案 0 :(得分:2)
您可以为此创建O(n)
算法。
步骤:
bucket[]
。(应该调整所有字符)bucket[]
中的每个元素初始化为0
。 bucket[]
处增加a[i]
。bucket[]
中运行另一个循环,如果bucket[i] > 0
,则将(char) i
附加到b[]
数组。代码:
#include <stdio.h>
#include <string.h>
int main()
{
char a[100], b[100];
int bucket[256] = {0};
int i;
printf("Enter the string:");
scanf("%s",a);
int n = strlen(a);
for(i = 0; i < n; ++i)
{
//Incrementing the character count of each character.
bucket[a[i]]++;
}
//Keep track of the index where the next character is to be appended.
int b_pos = 0;
for (i = 0; i < 256; ++i)
{
//Character occurs in a[], we don't care if it occurs once
//or twice, we just need one instance of it.
if (bucket[i] > 0)
{
b[b_pos] = (char) i;
b_pos++;
}
}
b[b_pos] = '\0';
printf("Modified string : %s",b);
}
答案 1 :(得分:0)
看看这个:
int main()
{
char a[100],b[100];
int i,n,j,count=0,k=0;
printf("ENTRE THE STRING \n");
scanf("%s",a);
n = strlen(a);
b[0] = a[0];
k = 1;
for(i=1;i<n;i++)
{
for(j=0;j<i;j++)
{
if(a[i] == b[j])
{
count = 1;
break;
}
}
if(count == 0)
{
b[k] = a[i];
k++;
}
else
{
count = 0;
}
}
b[k] = 0;
printf("RESULT %s",b);
return 0;
}