fool2fish/the-c-programming-language-exercise-answers

Probable Misunderstanding in Ex2.4

Closed this issue · 1 comments

While the usage of KMP algorithm is astounding and shows the coder's firm grasp of text processing (maybe earned from Dragon book?), the answer to Exercise 2.4 is probably inappropriate because of misunderstanding.
The original exercise says:

Write an alternate version of squeeze(s1,s2) that deletes each character in s1 that matches any character in the string s2.

A character in s1 should be deleted as long as it also exists in s2. In contrast, the implementation in this repo deletes the substring of s1. Other online resoource suggests the erroneous interpretation of Ex2.4 as well.

Here is my implementation. squeeze first scans s2 and records character occurrence to an array(with the size of one char, enough for ASCII), and then loops through s1 to delete matching characters.

#define SIZE 0xff                                                                                                                
void squeeze(char s1[], char s2[])
{
    char symbol[SIZE] = {};
    int i, j;

    for (i = 0; s2[i] != '\0'; ++i) {
       symbol[s2[i]] = 1;
    }

    i = j = 0;

    while (s1[i] != '\0') {
        while (symbol[s1[i]])
            ++i;
        s1[j++] = s1[i++];
    }

    s1[j] = '\0';
}

Best wishes!

Yep! You are right. I didn't read the question carefully. Thank you. I'll fix it soon, or maybe tomorrow, haha.

To my surprise, you know that I learned the KMP algorithm from the dragon book.

Expect to discuss more with you :-)