0ms C language Solution


  • 0
    N
    void convertToNumber(char* s, int **pVerArray, int *pVerCnt)
    {
        int verLmt = 20;
        int *versions = malloc(verLmt * sizeof(int));
        int cnt = 0, len = strlen(s), tmp, pre=0;
        for(int cur = 0; cur < len; ++cur)
        {
            if(s[cur] == '.')
            {
                if(pre == cur)
                {
                    tmp = 0;
                }
                else
                {
                    s[cur] = 0;
                    tmp = atoi(s+pre);
                    pre = cur + 1;
                    s[cur] = '.';
                }
                if(cnt == verLmt)
                {
                    int *newVersions =  malloc(verLmt * sizeof(int) * 2);
                    memmove(newVersions, versions, verLmt);
                    versions = newVersions;
                    verLmt *= 2;
                }
                versions[cnt++] = tmp;
            }
        }
        
        tmp = atoi(s+pre);
        if(cnt == verLmt)
        {
                int *newVersions =  malloc((verLmt +1) * sizeof(int));
                memmove(newVersions, versions, verLmt);
                versions = newVersions;
                verLmt++;
        }
        versions[cnt++] = tmp;
        
        //remove the ending zero
        while(cnt > 0 && versions[cnt - 1] == 0)
        {
            cnt--;
        }
        
        *pVerArray = versions;
        *pVerCnt = cnt;
        return;
    }
    int compareVersion(char* version1, char* version2) {
        int *versions1, verCnt1;
        convertToNumber(version1, &versions1, &verCnt1);
        
        int *versions2, verCnt2;
        convertToNumber(version2, &versions2, &verCnt2);
    
        for(int i =0; i < verCnt1 && i < verCnt2; ++i)
        {
            if(versions1[i]>versions2[i]) return 1;
            if(versions1[i]<versions2[i]) return -1;
        }
        if(verCnt1 > verCnt2) return 1;
        if(verCnt1 < verCnt2) return -1;
        return 0;
    }

Log in to reply
 

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