From a11d45d64e23dbb32600b8176f372630d6bce940 Mon Sep 17 00:00:00 2001 From: mnerv Date: Fri, 6 Oct 2023 09:54:24 +0200 Subject: [PATCH] Half done 5. leetcode --- leetcode/longestpalindromicsubstr.c | 85 +++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 leetcode/longestpalindromicsubstr.c diff --git a/leetcode/longestpalindromicsubstr.c b/leetcode/longestpalindromicsubstr.c new file mode 100644 index 0000000..b69c764 --- /dev/null +++ b/leetcode/longestpalindromicsubstr.c @@ -0,0 +1,85 @@ +#include +#include +#include +#include + +#define ENALBE_LOG 1 + +#if ENALBE_LOG == 1 +#define DEBUG_LOG(...) printf(__VA_ARGS__) +#else +#define DEBUG_LOG(...) +#endif + +char* longestPalindrome(char * input_str) { + const size_t len = strlen(input_str) + 1; // Include null termination + size_t start = 0; + size_t end = 0; + + size_t c_start = 0; + size_t c_end = 0; + bool is_first = true; + + while (start < len) { + bool is_palindrome = false; + end = start; + DEBUG_LOG("start: %llu\n", start); + for (size_t i = start; i < len; ++i) { + const size_t dist = end - start + 1; + is_palindrome = false; + DEBUG_LOG(" dist: %llu:\n", dist); + for (size_t j = 0; j < dist; ++j) { + const size_t start_it = start + j; + const size_t end_it = end - j; + DEBUG_LOG(" [%llu]%c = [%llu]%c: %s\n",start_it, input_str[start_it], end_it, input_str[end_it], input_str[start_it] == input_str[end_it] ? "true" : "false"); + if (input_str[start_it] == input_str[end_it]) { + is_palindrome = true; + } else { + is_palindrome = false; + } + } + if (is_palindrome && end - start > c_end - c_start) break; + ++end; + } + DEBUG_LOG("extracted: "); + for (size_t i = 0; i < end - start + 1; ++i) { + DEBUG_LOG("%c", input_str[start + i]); + } + DEBUG_LOG("\n"); + DEBUG_LOG("[%llu] -> [%llu], c: [%llu] -> [%llu]\n", start, end, c_start, c_end); + DEBUG_LOG("\n"); + if (is_palindrome && (end - start > c_end - c_start || is_first)) { + is_first = false; + c_start = start; + c_end = end; + DEBUG_LOG("candidate: %llu -> %llu\n", c_start, c_end); + } + ++start; + } + + DEBUG_LOG("wow\n"); + DEBUG_LOG("[%llu] -> [%llu]: size %llu\n", c_start, c_end, c_end - c_start + 1); + char* str = (char*)malloc((c_end - c_start + 2) * sizeof(char)); + memcpy(str, input_str + start, (c_end - c_start + 1) * sizeof(char)); + str[c_end - c_start + 1] = '\0'; + return str; +} + +void print_hex(const char* str) { + const size_t size = strlen(str) + 1; // Size of string with null termination + for (size_t i = 0; i < size; ++i) { + printf("0x%02x", str[i]); + if (i < size - 1) printf(" "); + else printf("\n"); + } +} + +int main() { + const char* input = "cbbd"; + printf("input: %s\n", input); + char* str = longestPalindrome(input); + printf("%s\n", str); + free(str); + return 0; +} +