char* str_rec[] = { ['2'] = "abc", ['3'] = "def", ['4'] = "ghi", ['5'] = "jkl", ['6'] = "mno", ['7'] = "pqrs", ['8'] = "tuv", ['9'] = "wxyz", }; int len_rec[] = { ['2'] = 3, ['3'] = 3, ['4'] = 3, ['5'] = 3, ['6'] = 3, ['7'] = 4, ['8'] = 3, ['9'] = 4, }; * 这里递归进行处理 * str指向当前要处理的字符指针 * ret已经申请好所有的空间。 */ void append_char(const char *a, char *str, char **ret) { if (!str || !(*str)) { return; } char *dic = str_rec[*str]; if (!dic || !(*dic)) return; size_t i = 0; size_t pos = str - a; while (ret[i][0]) { ret[i][pos] = *dic; i++; } const size_t curlen = i; char *p = dic + 1; while (*p) { size_t npos = (p-dic)*curlen; for (size_t i = 0; i < curlen; i++) { strcpy(ret[npos + i], ret[i]); ret[npos+i][pos] = *p; } p++; } append_char(a, str + 1, ret); } * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */ char** letterCombinations(char* digits, int* returnSize) { if (NULL == digits || *digits == 0) { *returnSize = 0; return NULL; } *returnSize = 1; char *p = digits; while (*p) { (*returnSize) *= len_rec[*p] > 0 ? len_rec[*p] : 1; p++; } * 结果字符串的长度是d_len + 1 */ int d_len = p - digits; size_t retSize = sizeof(char*) * (*returnSize + 1); char **ret = (char**)malloc(retSize); memset(ret, 0, retSize); for (size_t i = 0; i < *returnSize; i++) { size_t n = sizeof(char) * (d_len + 1); ret[i] = (char*)malloc(n); memset(ret[i], 0, n); } char *str = str_rec[*digits]; for (size_t i = 0; str[i]; i++) { ret[i][0] = str[i]; } append_char(digits, digits + 1, ret); return ret; }
|