LeetCode 5. Longest Palindromic Substring
2017-11-15 14:03
459 查看
Description
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.Example:
Input: “babad”
Output: “bab”
Note: “aba” is also a valid answer.
Code
char* longestPalindrome(char* s) { int n = strlen(s); char *r = malloc(n*sizeof(char)); int max_l = 0; int mid = (n % 2 == 0) ? n/2 : (n+1)/2; int m, i, j; i = j = mid-1; if(n <= 1) return s; while((i+max_l/2)<n){ m = 0; while((i-m>=0)&&(i+m<n)&&(s[i-m]==s[i+m])){ m++; } if(max_l < 2*(m-1)+1){ max_l = 2*(m-1)+1; memcpy(r,&s[i-m+1],2*(m-1)+1); } if((i+1 < n)&&(s[i]==s[i+1])){ m = 0; while((i-m>=0)&&(i+1+m<n)&&(s[i-m]==s[i+1+m])){ m++; } if(max_l < 2*m){ max_l = 2*m; memcpy(r,&s[i-m+1],2*m); } }else if((i-1>=0)&&(s[i]==s[i-1])){ m = 0; while((i-1-m>=0)&&(i+m<n)&&(s[i-1-m]==s[i+m])){ m++; } if(max_l < 2*m){ max_l = 2*m; memcpy(r,&s[i-m],2*m); } } i++; } while(j>=max_l/2){ if((j+1 < n)&&(s[j]==s[j+1])){ m = 0; while((j-m>=0)&&(j+1+m<n)&&(s[j-m]==s[j+1+m])){ m++; } if(max_l < 2*m){ max_l = 2*m; memcpy(r,&s[j-m+1],2*m); } } if((j-1>=0)&&(s[j]==s[j-1])){ m = 0; while((j-1-m>=0)&&(j+m<n)&&(s[j-1-m]==s[j+m])){ m++; } if(max_l < 2*m){ max_l = 2*m; memcpy(r,&s[j-m],2*m); } } m = 0; while((j-m>=0)&&(j+m<n)&&(s[j-m]==s[j+m])){ m++; } if(max_l < 2*(m-1)+1){ max_l = 2*(m-1)+1; memcpy(r,&s[j-m+1],2*(m-1)+1); } j--; } char *rr = malloc((max_l+1)*sizeof(char)); memset(rr,0,(max_l+1)*sizeof(char)); memcpy(rr,r,max_l); return rr; }
Discussions
1.Runtime: 6 ms2.The algorithm starts searching from the middle to save some time, but the code seems longer than starting from left or right end.
3.To allocate the memory of a string in C, remember to allocate one more byte after the actual string length to keep the end char ‘\0’, or you will get a error char when in the end of the string.
相关文章推荐
- leetCode:Longest Palindromic Substring
- LeetCode 5 Longest Palindromic Substring
- 5. Longest Palindromic Substring LeetCode题解
- LeetCode OJ5 Longest Palindromic Substring 小结
- LeetCode之5_Longest Palindromic Substring
- [C++]LeetCode: 99 Longest Palindromic Substring (最长回文子串)
- [Leetcode] Longest Palindromic Substring
- leetcode 5 Longest Palindromic Substring
- 《leetCode》:Longest Palindromic Substring
- [LeetCode]Longest Palindromic Substring
- leetcode之Longest Palindromic Substring
- LeetCode-5-Longest Palindromic Substring(动态规划)-Medium
- leetcode Longest Palindromic Substring
- leetcode5 Longest Palindromic Substring
- leetcode 5(Longest Palindromic Substring)golang实现
- [LeetCode] Longest Palindromic Substring 解题报告
- Leetcode练习 #5 Longest Palindromic Substring
- LeetCode 5 Longest Palindromic Substring(最长子序列)
- [LeetCode]Longest Palindromic Substring
- LeetCode 5. Longest Palindromic Substring