5. Longest Palindromic Substring
Posted yuhaowang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了5. Longest Palindromic Substring相关的知识,希望对你有一定的参考价值。
字符串遍历,从中间分出奇数回文和偶数回文两种情况不断更新长度。我一开陷入入误区把字符串分为奇偶结果偶数的可以过,基数的abb过不了。所以就是分析回文就好
char* longestPalindrome(char* s) { int len = strlen(s); if (len <= 1) { return s; } int start = 0; int maxlen = 0; for (int i = 1; i < len; i++) { int low = i - 1; int high = i; while (low >= 0 && high < len && s[low] == s[high]) { low--; high++; } if (high - low - 1 > maxlen) { maxlen = high - low - 1; start = low + 1; } low = i - 1; high = i + 1; while (low >= 0 && high < len && s[low] == s[high]) { low--; high++; } if (high - low - 1 > maxlen) { maxlen = high - low - 1; start = low + 1; } } char *arr = (char *)malloc(sizeof(char) * maxlen+1000); int i = 0; for (; i < maxlen; i++) { arr[i] = s[start++]; } arr[i] = ‘