Leetcode Letter Combinations of a Phone Number problem solution in C programming

In the Leetcode Letter Combinations of a Phone Number problem solution in C programming Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

Leetcode Letter Combinations of a Phone Number problem solution in C programming

char** letterCombinations(char* digits, int* returnSize) {
    char letterMatrix[10][5] = {" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    char letterLength[10] = {1, 1, 3, 3, 3, 3, 3, 4, 3, 4};
    bool empty = true;
    int count = 1;
    int length = strlen(digits);
    for (int i = 0; i < length; i++) {
        int digit = digits[i] - '0';
        if (letterLength[digit] > 0) {
            empty = false;
            count *= letterLength[digit];
        }
    }
    if (empty) {
        *returnSize = 0;
        return NULL;
    }
    *returnSize = count;
    char **result = calloc(count, sizeof(char *));
    for (int i = 0; i < count; i++) {
        *(result + i) = calloc(length + 1, sizeof(char));
    }
    int blockLeap = count;
    int blockNum = 1;
    for (int i = 0; i < length; i++) {
        int currentDigit = digits[i] - '0';
        int n = letterLength[currentDigit];
        int letterLeap = blockLeap / n;
        for (int j = 0; j < n; j++) {
            for (int k = 0; k < blockNum; k++) {
                for (int l = 0; l < letterLeap; l++) {
                    result[l + j * letterLeap + k * blockLeap][i] = letterMatrix[currentDigit][j];
                }
            }
        }
        blockLeap /= n;
        blockNum *= n;
    }
    return result;
}

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *