Created
August 6, 2013 16:17
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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