diff --git a/leetcode/DIRECTORY.md b/leetcode/DIRECTORY.md index 1bddc049..9288471e 100644 --- a/leetcode/DIRECTORY.md +++ b/leetcode/DIRECTORY.md @@ -108,6 +108,7 @@ | 1009 | [Complement of Base 10 Integer](https://leetcode.com/problems/complement-of-base-10-integer/) | [C](./src/1009.c) | Easy | | 1026 | [Maximum Difference Between Node and Ancestor](https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/description/) | [C](./src/1026.c) | Medium | | 1089 | [Duplicate Zeros](https://leetcode.com/problems/duplicate-zeros/) | [C](./src/1089.c) | Easy | +| 1147 | [Longest Chunked Palindrome Decomposition](https://leetcode.com/problems/longest-chunked-palindrome-decomposition/description/) | [C](./src/1147.c) | Hard | | 1184 | [Distance Between Bus Stops](https://leetcode.com/problems/distance-between-bus-stops/) | [C](./src/1184.c) | Easy | | 1189 | [Maximum Number of Balloons](https://leetcode.com/problems/maximum-number-of-balloons/) | [C](./src/1189.c) | Easy | | 1207 | [Unique Number of Occurrences](https://leetcode.com/problems/unique-number-of-occurrences/) | [C](./src/1207.c) | Easy | diff --git a/leetcode/src/1147.c b/leetcode/src/1147.c new file mode 100644 index 00000000..501060d0 --- /dev/null +++ b/leetcode/src/1147.c @@ -0,0 +1,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; +}