CareerCup-1.3

Design an algorithm and write code to remove the duplicate characters in a string without using any additional buffer

NOTE: One or two additional variables are fine. An extra copy of the array is not.

这道题做的时候思维上有问题。每次发现有重复的就将其后的向前移位。看了答案才明白不需要移位,中间留一段无效的地带就可以。

#include <iostream>
using namespace std;

void removeDuplicates(char* str) {
    if (str == NULL) return;
    char *p, *q, *tail;
    tail = str + 1;
    for(p=str; *p!='\0'; p++)
    {
        for(q=str; q<tail; q++)
        {
            if(*q == *p) break;
        }
        if(q==tail)
        {
            *tail++ = *p;
        }
    }
    *tail = '\0';
};

int main()
{
    char str[] = "aabcdefgeeadaa";
    removeDuplicates(str); 
    cout<<str;
    system("pause"); 
};

#include <iostream>
using namespace std;

void removeDuplicates(char* str) {
    if (str == NULL) return;
    char *p, *q, *tail;
    tail = str + 1;
    for(p=str; *p!='\0'; p++)
    {
        for(q=str; q<tail; q++)
        {
            if(*q == *p) break;
        }
        if(q==tail)
        {
            *tail++ = *p;
        }
    }
    *tail = '\0';
};

int main()
{
    char str[] = "aabcdefgeeadaa";
    removeDuplicates(str); 
    cout<<str;
    system("pause"); 
};

Comments

comments powered by Disqus