3ms C solution


  • 0
    V
    #define UPPER(a) ((97 <= (a) && (a) <= 122) ? (a) - 32 : (a))
    
    int keyLength(char* s);
    
    char* licenseKeyFormatting(char* S, int K)
    {
        int len, rem, c, i, j;
        char* key;
    
        // Length without dashes
        len = keyLength(S);
        
        // Length of first group
        rem = len % K;
        if (rem == 0) rem = K;
        
        // Length with dashes
        len += (len + K - 1) / K - 1;
        if (len < 0) len = 0;
    
        key = malloc(sizeof(char) * (len + 1));
    
        for (i = j = 0, c = K + 1 - rem; i < len;)
            // Add dashes
            if (c == K + 1)
                key[i++] = '-', c = 1;
            else {
                // Ignore dashes in original string
                if (S[j] != '-')
                    key[i++] = UPPER(S[j]), c++;
                j++;
            }
    
        key[len] = '\0';
    
        return key;
    }
    
    int keyLength(char* s)
    {
        int l;
    
        for (l = 0; *s != '\0'; s++)
            if (*s != '-')
                l++;
    
        return l;
    }
    

Log in to reply
 

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