Accepted as best, concise C solution


  • 0
    F
    /**
     * Return an array of size *returnSize.
     * Note: The returned array must be malloced, assume caller calls free().
     */
    void save(int **res, int *size, int *returnSize, int val) {
        if (*size == *returnSize) {
            *size += 1000;
            *res = realloc(*res, *size * sizeof(int));
        }
        (*res)[(*returnSize)++] = val;
    }
    int* findAnagrams(char* s, char* p, int* returnSize) {
        if (strlen(s) < strlen(p)) return 0;
        int size = 1000;
        int *res = malloc(size * sizeof(int));
        *returnSize = 0;
        
        int i, diff = 0, flag[256] = {0};
        for (i = 0; p[i]; i++) {
            if (s[i] == p[i]) continue;
            diff += ++flag[s[i]] > 0 ? 1 : -1;
            diff += --flag[p[i]] < 0 ? 1 : -1;
        }
        if (!diff) save(&res, &size, returnSize, 0);
        int j;
        for (j = i; s[j]; j++) {
            diff += ++flag[s[j]] > 0 ? 1 : -1;
            diff += --flag[s[j - i]] < 0 ? 1 : -1;
            if (!diff) save(&res, &size, returnSize, j - i + 1);
        }
        
        return res;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.