feat: add Longest Palindrome Substring solution (#1210)

* feat: add Longest Palindrome Substring solution

* fix: update formatting and allocate new results string

* fix: update formatting, fix bug related to the string copy

* fix: add parantheses for one line if statement

* fix: add comments for library inclusions
This commit is contained in:
Mindaugas 2023-02-25 20:35:50 +00:00 committed by GitHub
parent f6a326b268
commit 6e94adf066
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 53 additions and 0 deletions

View File

@ -9,6 +9,7 @@
| 2 | [Add Two Numbers](https://leetcode.com/problems/add-two-numbers) | [C](./src/2.c) | Medium |
| 3 | [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters) | [C](./src/3.c) | Medium |
| 4 | [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays) | [C](./src/4.c) | Hard |
| 5 | [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring) | [C](./src/5.c) | Medium |
| 6 | [Zigzag Conversion](https://leetcode.com/problems/zigzag-conversion) | [C](./src/6.c) | Medium |
| 7 | [Reverse Integer](https://leetcode.com/problems/reverse-integer) | [C](./src/7.c) | Medium |
| 8 | [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi) | [C](./src/8.c) | Medium |

52
leetcode/src/5.c Normal file
View File

@ -0,0 +1,52 @@
/**
* Find longest palindrome by traversing the string and checking how
* long palindrome can be constructed from each element by going left and right.
* Checking palindromes of types '..aa..' and '..bab..'
*/
#include <stdlib.h> /// for allocating new string via malloc()
#include <string.h> /// for copying the contents of the string via strncpy()
char * longestPalindrome(char * s) {
int si_max = 0, ei_max = 0, sz_max = 0, sz, i, delta_i;
char ch, *s_longest;
if (s[1] == '\0') return s;
for (ch = s[1], i = 1; ch != '\0'; ch = s[++i]) {
if (s[i - 1] == ch) {
sz = 2;
delta_i = 1;
while (i - 1 - delta_i >= 0 && s[i + delta_i] != '\0' && s[i - 1 - delta_i] == s[i + delta_i]) {
sz += 2;
delta_i += 1;
}
if (sz > sz_max) {
sz_max = sz;
si_max = i - 1 - delta_i + 1;
ei_max = i + delta_i - 1;
}
}
}
for (ch = s[0], i = 1; ch != '\0'; ch = s[++i]) {
sz = 1;
delta_i = 1;
while (i - delta_i >= 0 && s[i + delta_i] != '\0' && s[i - delta_i] == s[i + delta_i]) {
sz += 2;
delta_i += 1;
}
if (sz > sz_max) {
sz_max = sz;
si_max = i - delta_i + 1;
ei_max = i + delta_i - 1;
}
}
if ((s_longest = (char *) malloc(sizeof(s))) == NULL) {
return NULL;
}
strncpy(s_longest, s + si_max, sz_max);
s_longest[sz_max] = '\0';
return s_longest;
}