My C Solution


  • 0
    M

    /**

    • Return an array of size *returnSize.
    • Note: The returned array must be malloced, assume caller calls free().
      */

    char** letterCombinations(char* digits, int* returnSize) {
    int length = strlen(digits);
    int size = 1;

    if(length == 0)
        return NULL;
    
    for(int i = 0;i<length;i++) {
        if(digits[i] == '7' || digits[i] == '9')
            size *= 4;
        else
            size *= 3;
    }
    *returnSize = size;
    char **result = (char **)malloc(sizeof(char *) * (*returnSize));
    
    for(int i = 0;i < size;i++)
        result[i] = (char *)malloc(sizeof(char)*(length +1)) ;
    
    size = 1;
    char words[8][5] = { //one more space to store '\0'
        "abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"
    };
    
    for(int i =0;i<length;i++) {
        char* word = words[digits[i]-'2'];
        printf("%s",word);
        for (int j = 0; j < strlen(word);j++) {
            int index = j * size;
            for(int k = 0; k< size;k++) {
                if(j> 0 && size >1)
                   strcpy(result[index + k], result[index + k - size]);
                result[index + k][i] = word[j];
                result[index + k][i+1] = '\0';
            } 
        }
        size *= strlen(word); 
    }
    
    return result;
    

    }


Log in to reply
 

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