diff options
Diffstat (limited to 'Computer_Science/leetcode/5-longest_palindromic_substring.c')
| -rw-r--r-- | Computer_Science/leetcode/5-longest_palindromic_substring.c | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/Computer_Science/leetcode/5-longest_palindromic_substring.c b/Computer_Science/leetcode/5-longest_palindromic_substring.c new file mode 100644 index 0000000..ee65b8e --- /dev/null +++ b/Computer_Science/leetcode/5-longest_palindromic_substring.c @@ -0,0 +1,34 @@ +void extend(char *s, int len, int i, int j, int *lo, int *hi) +{ + while(i >= 0 && i < len && s[i] == s[j]) { + i--; + j++; + } + + if(j - i > *hi - *lo) { + *lo = i; + *hi = j; + } +} + +char* longestPalindrome(char* s) { + int *lo, *hi; + int len = strlen(s); + + lo = malloc(sizeof(int)); + hi = malloc(sizeof(int)); + + *lo = *hi = 0; + if(len < 2) + return s; + + for(int i = 0; i < len - 1; i++) { + extend(s, len, i, i, lo, hi); + extend(s, len, i, i + 1, lo, hi); + } + + *(s + (*hi)) = '\0'; + return s + *lo + 1; +} + + |
