From 0db3ba54c9b6e7e25d0336db7723b61415c527f3 Mon Sep 17 00:00:00 2001 From: julienChemillier <66684524+julienChemillier@users.noreply.github.com> Date: Sun, 4 Sep 2022 09:22:35 +0200 Subject: [PATCH] Add 5 in language c --- c/5-Longest-Palindromic-Substring.c | 42 +++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 c/5-Longest-Palindromic-Substring.c diff --git a/c/5-Longest-Palindromic-Substring.c b/c/5-Longest-Palindromic-Substring.c new file mode 100644 index 000000000..884f9dc26 --- /dev/null +++ b/c/5-Longest-Palindromic-Substring.c @@ -0,0 +1,42 @@ + +/* +Given a string s, return the longest palindromic substring in s. +Time: O(n^2) +Space: O(1) +*/ + +char* longestPalindrome(char * s){ + int pos=0; + int lenmax=1; + for (int i=0; s[i]!='\0'; i++){ + int g=i, d=i; + while (g>=0 && s[d]!='\0' && s[g]==s[d]){ + g-=1; + d+=1; + } + d--; + g++; + if (d-g>=lenmax){ + lenmax=d-g+1; + pos=g; + } + g=i,d=i+1; + while (g>=0 && s[d]!='\0' && s[g]==s[d]){ + g-=1; + d+=1; + } + d--; + g++; + + if (d-g>=lenmax){ + lenmax=d-g+1; + pos=g; + } + } + char* new_s = (char*)malloc(sizeof(char)*(lenmax+1)); + new_s[lenmax]='\0'; + for (int i=0; i