Algorithm
OJ address
Leetcode website : 5. Longest Palindromic Substring
Description
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
Solution in C
#include
#include
#include
char a[1002];
char* longestPalindrome(char* s) {
if (s[0] == '\0') return s;
int i, left, right, max, length, maxleft, maxright, mark;
i = left = right = max = length = maxleft = maxright = mark = 0;
while (s[i] != '\0') {
if (mark == 0) left = i-1;
else left = i;
right = i+1;
while (s[left] == s[right] && left>=0) {
left--;
right++;
}
if (mark) {
++i;
mark = 0;
length = right-left+1-2;
}
else {
mark = 1;
length = (i-(left+1))*2+1;
}
if (max < length) {
maxleft = ++left;
maxright = --right;
max = length;
}
}
int j=0;
while (maxright>=maxleft) a[j++] = s[maxleft++];
a[j] = '\0';
return a;
}
int main(int argc, char const *argv[])
{
char *s = "babad\0";
char *d = longestPalindrome(s);
printf("%s\n", d);
return 0;
}
My Idea
题目含义是,打印出最长的会问字符串,回文串就是一个正读和反读都一样的字符串,比如“level”或者“noon”等等就是回文串。
想到的版本就是搜索字符,然后两边查找字符是否相同,相同则继续两边扩散继续查找字符是否相同。
需要注意的第一点是,奇数和偶数的回文字符串解法不同哦。其他就没啥要注意的了,以上解法时间复杂度O(n2),
Runtime: 8 ms, faster than 78.44% of C online submissions for Longest Palindromic Substring.
看到这个结果就知道一定还有更快的0ms方法,那就是传说中的manacher算法?这种出奇制胜的算法我是想不到的,我看了下,也不是一般人能想到的。即使看了一遍以后还是会忘,毕竟不是通用的解法,是一些出奇制胜的想法。
之前喜欢用C语言和python做,但是发现这个题目用不到STL,所以没必要用python在刷一遍了。