C solution, fail with some cases


  • 0
    O
    char* licenseKeyFormatting(char* S, int K) {
        int i;
        int clen = 0;
        for(i = 0; i < strlen(S); i++){
            if(S[i] != '-'){ 
                clen++;
                if(S[i] - '0' > 9 && S[i] - 'A' > 26){
                    S[i] = (char)(S[i] + 'A' - 'a');
                }
            }
        }
        if(clen == 0) return "";
        int n = clen / K - 1;
        //printf("n = %d\n", n);
        int m = clen % K;
        int temp = 0;
        if(m != 0){
            temp = m;
            n = n + 1;
        } 
        //printf("%d", m);
        bool first = true;
        int h = 0;
        printf("result len = %d",clen + n);
        char* result = malloc((clen + n) * sizeof(char));
        for(i = 0; i < strlen(S); i++){
            if(temp == 0){
                temp = K;
                if(first && m == 0) {
                    first = false;
                }
                else{
                    result[h] = '-';
                    h++;
                }
            } 
            if(S[i] != '-'){
                result[h] = S[i];
                h++;
                temp--;
            }
        }
        //printf("%d",strlen(result));
        return result;
    }
    

  • 0
    O

    @owen0271
    Code fails for test case:

    Input:
    "2-4A0r7-4k"
    3
    Output:
    "24-A0R-74K��4"
    Expected:
    "24-A0R-74K"

    where did that last part of the output come from? Can someone please help me?


  • 0
    R

    Not that I scanned your whole code but I don't see any NULL terminations


  • 0
    O

    Thanks! Now I understand what happened and post this new approach. This one works

    char* licenseKeyFormatting(char* S, int K) {
        char* result = (char*)malloc(strlen(S)*2*sizeof(char));
        int i, j = K, h = 0, count = 0;
        for(i = strlen(S)-1; i >= 0; i--){
            if(j == 0){
                result[h] = '-';
                j = K;
                h++;
            } 
            if(S[i] != '-'){
                if(S[i] - 'a' >= 0 && S[i] - 'a' <= 26){
                    result[h] = (char)(S[i] - 'a' + 'A');
                }
                else{
                    result[h] = S[i];
                }
                j--;
                h++;
                count++;
            }
        }
        if(count == 0) return "";
        if(count % K == 0) result[count+count/K - 1] = '\0';
        else result[count+count/K] = '\0';
        char* temp = (char*)malloc(strlen(S)*2*sizeof(char));
        int len = strlen(result);
        for(i = 0; i < len; i++){
            temp[i] = result[len - i - 1];
        }
    
    return temp;
    

    }


Log in to reply
 

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