Skip to content

Commit 3c5f33f

Browse files
add problem 17 and test function
1 parent 1b40dcc commit 3c5f33f

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/*
2+
* Given a digit string, return all possible letter combinations that the number could represent.
3+
4+
* Created by supercoderx on 2017/8/9.
5+
*/
6+
#include <stdio.h>
7+
#include <stdlib.h>
8+
#include <string.h>
9+
10+
char **letterCombinations(char *digits, int *returnSize) {
11+
char *map[] = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
12+
int mapLen[] = {1, 1, 3, 3, 3, 3, 3, 4, 3, 4};
13+
int len = 0, count = 0, id = 0;
14+
char *tmp = digits, **result = NULL;
15+
16+
while (*tmp != '\0') {
17+
len++;
18+
tmp++;
19+
}
20+
(*returnSize) = 0;
21+
22+
for (int i = 0; i < len; i++) {
23+
id = digits[i] - 0x30;
24+
count = mapLen[id];
25+
if (i == 0) {
26+
result = malloc(sizeof(char *) * count);
27+
for (int j = 0; j < count; j++) {
28+
result[j] = malloc(sizeof(char) * (len + 1));
29+
result[j][0] = map[id][j];
30+
result[j][len] = '\0';
31+
}
32+
*returnSize = count;
33+
} else {
34+
result = realloc(result, sizeof(char *) * (*returnSize) * count);
35+
for (int j = 0; j < count; j++) {
36+
37+
for (int k = 0; k < *returnSize; k++) {
38+
if (j > 0) {
39+
result[k + j * (*returnSize)] = malloc(sizeof(char) * (len + 1));
40+
result[k + j * (*returnSize)][len] = '\0';
41+
strncpy(result[k + j * (*returnSize)], result[k], i);
42+
}
43+
result[k + j * (*returnSize)][i] = map[id][j];
44+
}
45+
}
46+
(*returnSize) *= count;
47+
}
48+
}
49+
return result;
50+
}
51+
52+
void testLetterCombinations() {
53+
char str[] = "23";
54+
int count = 0;
55+
char **result = letterCombinations(str, &count);
56+
for (int i = 0; i < count; i++) {
57+
printf("%s,", result[i]);
58+
}
59+
}

0 commit comments

Comments
 (0)