Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1021 from julienChemillier/patch-3
Browse files Browse the repository at this point in the history
Add 5 in language c
  • Loading branch information
Ahmad-A0 authored Sep 5, 2022
2 parents da1dd94 + 0db3ba5 commit c2fced0
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions c/5-Longest-Palindromic-Substring.c
Original file line number Diff line number Diff line change
@@ -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<lenmax; i++){
new_s[i]=s[i+pos];
}
return new_s;
}

0 comments on commit c2fced0

Please sign in to comment.