Skip to content

Instantly share code, notes, and snippets.

@airekans
Created August 6, 2013 16:17
Show Gist options
  • Save airekans/6166017 to your computer and use it in GitHub Desktop.
Save airekans/6166017 to your computer and use it in GitHub Desktop.
[OJ] Careercup Top 150(1.3): Solution: 1. O(n^2): loop directly to remove duplicate, then compact. 2. O(lg n): sort then remove duplicate, then compact.
// O(n^2) solution
void remove_duplicate(char* s)
{
const int size = strlen(s);
for (int i = 0; i < size - 1; ++i)
{
if (s[i] == '\0')
{
continue;
}
for (int j = i + 1; j < size; ++j)
{
if (s[i] == s[j])
{
s[j] = '\0';
}
}
}
compact(s, size);
}
void compact(char* s, const int size)
{
int count = 0;
for (int i = 0; i < size; ++i)
{
if (s[i] != '\0')
{
s[count++] = s[i];
}
}
s[count] = '\0';
}
// O(lg n) solution
int char_cmp(void* a, void* b)
{
const char c_a = *(char*)a;
const char c_b = *(char*)b;
return c_a - c_b;
}
void remove_duplicate2(char* s)
{
const int size = strlen(s);
qsort(s, size, sizeof(char), &char_cmp);
for (int i = 0; i < size - 1; ++i)
{
if (s[i] == s[i + 1])
{
s[i] = '\0';
}
}
compact(s, size);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment