Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e8869f3

Browse files
committed
"Decode Ways": fix memory leak
1 parent fbb8e06 commit e8869f3

File tree

1 file changed

+23
-9
lines changed

1 file changed

+23
-9
lines changed

‎src/91.c‎

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,39 @@
11
#include <stdio.h>
22
#include <stdlib.h>
33
#include <string.h>
4+
#include <assert.h>
45

56
int numDecodings(char *s) {
7+
if (s == NULL) return 0;
68
int len = strlen(s);
79
if (len == 0) return 0;
8-
int *d = (int *)calloc(len + 1, sizeof(int));
10+
int *dp = (int *)malloc((len + 1) * sizeof(int));
911
int i;
10-
d[0] = 1;
11-
d[1] = (s[0] != '0') ? 1 : 0;
12+
dp[0] = 1;
13+
dp[1] = (s[0] == '0') ? 0 : 1;
1214
for (i = 2; i < len + 1; i++) {
13-
if (s[i - 1] != '0') /*1 step*/
14-
d[i] += d[i - 1];
15+
dp[i] = (s[i - 1] == '0') ? 0 : dp[i - 1]; /*1 step*/
1516
if (s[i - 2] == '1' || (s[i - 2] == '2' && s[i - 1] <= '6')) /*2 steps*/
16-
d[i] += d[i - 2];
17+
dp[i] += dp[i - 2];
1718
}
18-
return d[len];
19+
int ans = dp[len];
20+
free(dp);
21+
return ans;
1922
}
2023

2124
int main() {
22-
char s[] = "301";
23-
printf("%d\n", numDecodings(s));
25+
char s0[] = "301";
26+
char s1[] = "";
27+
char s2[] = "0";
28+
char s3[] = "01";
29+
char s4[] = "112";
30+
assert(numDecodings(s0) == 0);
31+
assert(numDecodings(s1) == 0);
32+
assert(numDecodings(s2) == 0);
33+
assert(numDecodings(s3) == 0);
34+
assert(numDecodings(s4) == 3);
35+
36+
printf("all tests passed!\n");
37+
2438
return 0;
2539
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /