-
-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
Copy path1147.c
49 lines (39 loc) · 1.31 KB
/
1147.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#define max(a,b) (((a)>(b))?(a):(b))
bool equalSubstrings(char* text, int firstIndex, int secondIndex, int length){
for (int i = 0; i < length; i++){
if (text[firstIndex + i] != text[secondIndex + i]){
return false;
}
}
return true;
}
int longestDecompositionDpCached(char* text, int textLen, int index, int* dp){
if (2 * index >= textLen){
return 0;
}
if (dp[index] == 0){
dp[index] = longestDecompositionDp(text, textLen, index, dp);
}
return dp[index];
}
int longestDecompositionDp(char* text, int textLen, int index, int* dp){
char ch = text[index];
int result = 1;
for (int i = 0; i < (textLen - 2 * index) / 2; i++){
if (ch == text[textLen - 1 - index - i]
&& equalSubstrings(text, index, textLen - 1 - index - i, i + 1)){
return max(result, 2 + longestDecompositionDpCached(text, textLen, index + i + 1, dp));
}
}
return result;
}
// Dynamic programming. Up -> down approach.
// Runtime: O(n*n)
// Space: O(n)
int longestDecomposition(char * text){
int textLen = strlen(text);
int* dp = calloc(textLen, sizeof(int));
int result = longestDecompositionDpCached(text, textLen, 0, dp);
free(dp);
return result;
}