Problem
Remove duplicate characters in a string, you cannot use additional buffer
Solution
#include <iostream>
using namespace std;
void add_ch(char *str, char c)
{
while(*str) str++;
*str = c;
*(str + 1) = '\0';
}
void del_first_ch(char *str)
{
if(str == NULL)
return;
while(*(str + 1)){
*str = *(str + 1);
str ++;
}
*str = '\0';
}
void remove_duplicates(char *str)
{
int tail = 1;
int i, j;
if(NULL == str)
return;
char *tmp = str;
while(*tmp){
tmp ++;
}
int len = tmp - str;
if(len < 2)
return;
for(i = 1; i < len; i++){
for(j = 0; j < tail; j ++){
if(str[i] == str[j]){
break;
}
}
if(j == tail){
str[tail] = str[i];
tail ++;
}
}
str[tail] = '\0';
}
int main(int argc, char* argv[])
{
char str_list[10][20] =
{"abac",
"aaaa",
"",
"aaaabbbbb",
"abac",
"tba da"};
for(int i = 0; i < 6; ++i){
remove_duplicates(str_list[i]);
cout << str_list[i] << endl;
}
}
Output
abc
a
ab
abc
tba d