Offsetting the entire line left in one place will make this O (n ^ 2) algorithm efficient. You can do this locally in linear time:
void Remove (char * src, const char * match) {
char * dest = src;
for (;;) {
char ch = *src++;
if (!strchr (match, ch)) *dest++ = ch;
if (!ch) break;
}
}
I assume they have zero termination. If this is not the case, then you also need to go the length and change the algorithm accordingly. In particular, you cannot use strchr. Just for completeness, here is a version that works with char arrays (not null terminated).
int Remove (char[] str, int srclen, char[] match, int matchlen) {
int dst = 0, found;
for (int src = 0; src < srclen; src++) {
char ch = str[src];
found = 0;
for (int i = 0; i < matchlen && !found; i++)
if (match[i] == ch) found = 1;
if (!found) str[dst++] = ch;
}
return dst;
}
And finally, it is as close as possible to O (n), as we are going to get, I think. I assume 8-bit characters here and create a lookup table so that it runs in O (n) + O (m), where m is the length of the match string.
int Remove (char* str, int srclen, char* match, int matchlen) {
bool found[256];
for (int i = 0; i < 256; i++) found[i] = 0;
for (int i = 0; i < matchlen; i++) found[match[i]] = 1;
int dst = 0;
for (int src = 0; src < srclen; src++) {
char ch = str[src];
if (!found[ch]) str[dst++] = ch;
}
return dst;
}
source
share