【leetcode】子域名访问计数

char ** subdomainVisits(char ** cpdomains, int cpdomainsSize, int* returnSize){
    char** arr = (char**)calloc(1000,sizeof(char*));
    int* hash = (int*)calloc(1000,sizeof(int));
    int num = 0;
    char* p = NULL;
    int n = 0;
    int flag = true;
    int i,j,k;
    int x;
    for (i=0; i<cpdomainsSize; i++)
    {
        sscanf(cpdomains[i],"%d",&num); // 把字符串前面的数字转成数字
        x = 0;
        for (j=0; j<strlen(cpdomains[i]); j++)
        {
            if (x > 2) break;  //因为最多出现 一个空格两个. 超过的话后面就没分级域名了
            if (cpdomains[i][j] == ' ' || cpdomains[i][j] == '.')
            {

                x++;
                p = &cpdomains[i][j+1];
                for (k=0; k<n; k++) //遍历arr,如果有相同域名则hash表数量累加,如果新出现就添加进arr
                {
                    if (arr[k] && !strcmp(p,arr[k]))
                    {
                        hash[k] += num;
                        flag = false;
                    }
                }
                if (flag) 
                {
                    arr[n] = p;
                    hash[n++] = num;
                }
                flag = true;
            }        
        }
    }
    
    for (i=0; i<n; i++)
    {
        char* count = (char*)calloc(100,sizeof(char));
        sprintf(count,"%d",hash[i]);
        arr[i] = strcat(strcat(count," "),arr[i]); //把数字和域名拼接放回arr
    }
    *returnSize = n;
    return arr;
}
原文地址:https://www.cnblogs.com/ganxiang/p/13608531.html