-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0005.longest_palindromic_substring_M.c
49 lines (48 loc) · 1.2 KB
/
0005.longest_palindromic_substring_M.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* https://leetcode.com/problems/longest-palindromic-substring/description/
* 2017/02
* 83 ms
*/
char * longestPalindrome(char * s)
{
int len = strlen(s);
char * palindrome = NULL;
if(strlen(s) < 2)
{
palindrome = (char *)malloc(len + 1);
palindrome[len] = '\0';
strncpy(palindrome, s, len);
return palindrome;
}
int max_len = 1;
int begin = 0;
int end = 1;
for(int idx = 0; idx < len; idx ++)
{
for(int next_idx = len - 1; next_idx > idx + max_len - 1; next_idx --)
{
if(s[next_idx] != s[idx])
{
continue;
}
int left = idx + 1;
int right = next_idx - 1;
while(left < right && s[left] == s[right])
{
left ++;
right --;
}
if(left >= right)
{
max_len = next_idx - idx + 1;
begin = idx;
end = next_idx + 1;
break;
}
}
}
palindrome = (char *)malloc(end - begin + 1);
palindrome[end - begin] = '\0';
strncpy(palindrome, s + begin, end - begin);
return palindrome;
}