/*
https://leetcode.cn/problems/longest-palindromic-substring/?favorite=2cktkvj
给你一个字符串 s,找到 s 中最长的回文子串。
如果字符串的反序与原始字符串相同,则该字符串称为回文字符串。
*/
/*
I got two methonds:
1. do as each char as the center of a palindromic to check the length,
its time O(N*N)
2. revert the string as string, find orig-string and revert-string max
common same substring, it shall be a O(N*N) time & O(N*N) space
*/
// here use the 1 methond
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void find_max_palindrome_string(const char *str)
{
int length = strlen(str);
int max = 0, start = 0, pos = 0, i = 0;
for (pos = 0; pos < length; pos++) {
//str[pos] as center of palindrome string
for (i = 1; ((pos - i) >= 0) && ((pos + i) < length); i++) {
if (str[pos -i] != str[pos + i])
break;
}
int tmp = 2 * (i - 1) + 1;
if (tmp > max) {
max = tmp;
start = pos + 1 - i;
}
if (str[pos] != str[pos + 1])
continue;
//if str[pos] == str[pos + 1], it could be even length
for (i = 1; ((pos - i) >= 0) && ((pos + 1 + i) < length); i++) {
if (str[pos -i] != str[pos + 1 + i])
break;
}
tmp = 2 * i;
if (tmp > max) {
max = tmp;
start = pos + 1 - i;
}
}
printf("max palindrome string: len=%d, from=%d, string: ", max, start);
for (i = 0; i < max; i++) {
putchar(str[i + start]);
}
}
int main(int argc, char *argv[])
{
if (argc != 2) {
printf("To find the max palindrom string, please input a string!\n");
return 0;
}
find_max_palindrome_string(argv[1]);
return 0;
}
查找最长回文子串
最新推荐文章于 2023-05-22 20:43:51 发布