Files
leetcode/leetcode/longestpalindromicsubstr.c
T
2023-10-06 13:00:16 +02:00

84 lines
2.5 KiB
C

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#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;
while (start < len) {
bool is_palindrome = false;
end = start;
DEBUG_LOG("start: %lu\n", start);
for (size_t i = start; i < len; ++i) {
const size_t dist = end - start + 1;
is_palindrome = false;
DEBUG_LOG(" dist: %lu:\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(" [%lu]%c = [%lu]%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) 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("[%lu] -> [%lu], c: [%lu] -> [%lu]\n", start, end, c_start, c_end);
DEBUG_LOG("\n");
if (is_palindrome && end - start > c_end - c_start) {
c_start = start;
c_end = end;
DEBUG_LOG("candidate: %lu -> %lu\n", c_start, c_end);
}
++start;
}
DEBUG_LOG("wow\n");
DEBUG_LOG("[%lu] -> [%lu]: size %lu\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;
}