5. Longest Palindromic Substring

来源:互联网 发布:访问通用顶级域名 编辑:程序博客网 时间:2024/06/06 19:06

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.

Example:

Input: "cbbd"Output: "bb"
可以画张图理解一下。
// 使用算法manacher , 充分利用对称性char* longestPalindrome(char* s) {int* radius;char* t;int tLength, sLength, i, j;int maxIndex, step;//插入字符使整个字符数组奇数化sLength = strlen(s);t = (char*) calloc(sLength * 2 + 1,sizeof(char));for(i=0;i<sLength;i++){t[i*2] = '#';t[i*2+1] = s[i];}tLength = sLength * 2 + 1;t[tLength - 1] = '#';//用于记录以该点为中心的回文半径 包括我刚才插入进去的字符radius = (int*) calloc(tLength, sizeof(int)); //计算每个点的回文半径for(maxIndex = 0, radius[maxIndex] = 0, step = 1; maxIndex + step < tLength;){//在当前最大回文的范围之外if(step > radius[maxIndex])radius[step + maxIndex] = 0;//之内else{if(step + radius[maxIndex - step] > radius[maxIndex])radius[maxIndex + step] = radius[maxIndex] - step;else radius[maxIndex + step] = radius[maxIndex - step];}i = maxIndex + step + radius[maxIndex + step] + 1;j = maxIndex + step - radius[maxIndex + step] - 1;while(i<tLength && j >= 0 && t[i++] == t[j--])radius[maxIndex + step]++;if(radius[maxIndex + step] > radius[maxIndex]){maxIndex += step;step = 1;}else step += 1;}if(t[maxIndex] == '#') {s[maxIndex/2 + radius[maxIndex]/2] = '\0';return s + maxIndex / 2  - radius[maxIndex] / 2;}else {s[(maxIndex - 1)/2+(radius[maxIndex] - 1)/2 + 1] = '\0';return s + (maxIndex - 1)/2 - (radius[maxIndex] - 1)/2;}}

0 0
原创粉丝点击