Most common substring of length X

前端 未结 8 2155
没有蜡笔的小新
没有蜡笔的小新 2021-02-09 13:49

I have a string s and I want to search for the substring of length X that occurs most often in s. Overlapping substrings are allowed.

For example, if s=\"aoaoa\" and X=3

8条回答
  •  无人及你
    2021-02-09 14:35

    Here is a version I did in C. Hope that it helps.

    #include 
    #include 
    #include 
    
    int main(void)
    {
        char *string = NULL, *maxstring = NULL, *tmpstr = NULL, *tmpstr2 = NULL;
        unsigned int n = 0, i = 0, j = 0, matchcount = 0, maxcount = 0;
    
        string = "aoaoa";
        n = 3;
    
        for (i = 0; i <= (strlen(string) - n); i++) {
            tmpstr = (char *)malloc(n + 1);
            strncpy(tmpstr, string + i, n);
            *(tmpstr + (n + 1)) = '\0';
            for (j = 0; j <= (strlen(string) - n); j++) {
                tmpstr2 = (char *)malloc(n + 1);
                strncpy(tmpstr2, string + j, n);
                *(tmpstr2 + (n + 1)) = '\0';
                if (!strcmp(tmpstr, tmpstr2))
                    matchcount++;
            }
            if (matchcount > maxcount) {
                maxstring = tmpstr;
                maxcount = matchcount;
            }
            matchcount = 0;
        }
    
        printf("max string: \"%s\", count: %d\n", maxstring, maxcount);
    
        free(tmpstr);
        free(tmpstr2);
    
        return 0;
    }
    

提交回复
热议问题