【leetcode】子域名訪問計數
阿新 • • 發佈:2020-09-03
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;
}