Solution #1: Let us first consider the case when extra buffer is not allowed. Scan every character in the string and compare it with every previous character, if it is a duplicate then ignore it, otherwise copy it. This approach will have a time complexity of O(n^2). Here is the code,
void removeDuplicates(char* ptr) { int end = 1; int length = strlen(ptr); int current; int i; current = 1; for(end=1; end<length; end++) { for(i=0; i<end; i++) { if(ptr[end] == ptr[i]) break; } if(i == end) { ptr[current] = ptr[i]; current++; } } ptr[current] = 0; } int main(int argc, char** argv) { char str[256] = {0,}; gets(str); removeDuplicates(str); printf("%s\n", str); return 1; }
2) Now, let's consider the case when we have the luxury of using extra memory. Also consider that the string is made up of extended ASCII characters. So let's make a bit array of 256 bits. Now, we can scan the string and use this array to keep a track of all the characters we encounter and ignore the duplicate ones.
2 comments:
for(i=0; i<end; i++)
.
.
.
if(i == end)
How can i be equal to end?
Ignore the i==end comment.
Post a Comment