|
| 1 | +#include <stdio.h> |
| 2 | +#include <string.h> |
| 3 | +#include <stdbool.h> |
| 4 | + |
| 5 | +#define MAX_LENGTH 1000 |
| 6 | + |
| 7 | +int expandAroundCenter(const char* s, int left, int right) { |
| 8 | + while (left >= 0 && right < strlen(s) && s[left] == s[right]) { |
| 9 | + left--; |
| 10 | + right++; |
| 11 | + } |
| 12 | + return right - left - 1; |
| 13 | +} |
| 14 | + |
| 15 | +bool longestPalindromicSubstring(const char* s, char* result) { |
| 16 | + if (s == NULL || strlen(s) == 0) { |
| 17 | + strcpy(result, ""); |
| 18 | + return false; |
| 19 | + } |
| 20 | + |
| 21 | + int start = 0, maxLength = 0; |
| 22 | + int len = strlen(s); |
| 23 | + |
| 24 | + for (int i = 0; i < len; i++) { |
| 25 | + int len1 = expandAroundCenter(s, i, i); |
| 26 | + int len2 = expandAroundCenter(s, i, i + 1); |
| 27 | + int len = (len1 > len2) ? len1 : len2; |
| 28 | + |
| 29 | + if (len > maxLength) { |
| 30 | + start = i - (len - 1) / 2; |
| 31 | + maxLength = len; |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + if (maxLength > 1) { |
| 36 | + strncpy(result, s + start, maxLength); |
| 37 | + result[maxLength] = '\0'; |
| 38 | + return true; |
| 39 | + } |
| 40 | + |
| 41 | + strcpy(result, ""); |
| 42 | + return false; |
| 43 | +} |
| 44 | + |
| 45 | +int main(int argc, char* argv[]) { |
| 46 | + if (argc != 2) { |
| 47 | + printf("Usage: please provide a string that contains at least one palindrome\n"); |
| 48 | + return 1; |
| 49 | + } |
| 50 | + |
| 51 | + const char* input = argv[1]; |
| 52 | + char result[MAX_LENGTH]; |
| 53 | + |
| 54 | + if (longestPalindromicSubstring(input, result) && strlen(result) > 0) { |
| 55 | + printf("%s\n", result); |
| 56 | + } else { |
| 57 | + printf("Usage: please provide a string that contains at least one palindrome\n"); |
| 58 | + } |
| 59 | + |
| 60 | + return 0; |
| 61 | +} |
0 commit comments