Finding common characters in two strings

前端 未结 13 2574
终归单人心
终归单人心 2020-12-15 14:09

I am coding for the problem in which we got to count the number of common characters in two strings. Main part of the count goes like this

for(i=0; i < st         


        
13条回答
  •  南方客
    南方客 (楼主)
    2020-12-15 14:37

    Your current code is O(n^3) because of the O(n) strlens and produces incorrect results, for example on "aa", "aa" (which your code will return 4).

    This code counts letters in common (each letter being counted at most once) in O(n).

    int common(const char *a, const char *b) {
        int table[256] = {0};
        int result = 0;
        for (; *a; a++)table[*a]++;
        for (; *b; b++)result += (table[*b]-- > 0);
        return result;
    }
    

    Depending on how you define "letters in common", you may have different logic. Here's some testcases for the definition I'm using (which is size of the multiset intersection).

    int main(int argc, char *argv[]) {
        struct { const char *a, *b; int want; } cases[] = {
            {"a", "a", 1},
            {"a", "b", 0},
            {"a", "aa", 1},
            {"aa", "a", 1},
            {"ccc", "cccc", 3},
            {"aaa", "aaa", 3},
            {"abc", "cba", 3},
            {"aasa", "asad", 3},
        };
        int fail = 0;
        for (int i = 0; i < sizeof(cases) / sizeof(*cases); i++) {
            int got = common(cases[i].a, cases[i].b);
            if (got != cases[i].want) {
                fail = 1;
                printf("common(%s, %s) = %d, want %d\n",
                       cases[i].a, cases[i].b, got, cases[i].want);
            }
        }
        return fail;
    }
    

提交回复
热议问题