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”
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-palindromic-substring
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
char * longestPalindrome(char * s){
int len = strlen(s);
int maxSubStrLen = 0;
int startIdx, endIdx;
int searchIdx = 0, searchLen = 1;
int i, m, n;
if (len <= 1) {
return s;
}
while (searchIdx < len) {
for (i = searchIdx + 1; i < len; i++){
if (s[searchIdx] != s[i]) {
break;
}
searchLen++;
}
m = i;
n = searchIdx - 1;
while ((n >= 0) && (m < len)) {
if (s[n] != s[m]) {
break;
}
m++;
n--;
searchLen += 2;
}
if (searchLen > maxSubStrLen){
maxSubStrLen = searchLen;
startIdx = n + 1;
endIdx = m - 1;
}
searchLen = 1;
searchIdx ++;
}
s[endIdx + 1] = '\0';
return &s[startIdx];
}
作者:yang-le-duo-48
链接:https://leetcode-cn.com/problems/longest-palindromic-substring/solution/cyu-yan-bian-li-xian-zhao-zhong-xin-zi-chuan-zai-c/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
#define max(a,b) (((a) > (b)) ? (a) : (b))
char * longestPalindrome(char * s){
int start = 0, end = 0;
int len = 0;
int len1 = 0;
int len2 = 0;
if (strlen(s) <= 1)
return s;
for (int i = 0; i < strlen(s); i++) {
len1 = expandaroundcenter(s, i, i);
len2 = expandaroundcenter(s, i, i+1);
len = max(len1, len2);
if (len > end - start) {
start = i - ((len - 1)>>1);
end = i + (len>>1);
}
}
char *p = malloc(sizeof(char) * (end - start + 2));
strncpy(p, s + start, end - start + 1);
p[end - start + 1] = '\0';
return p;
}
int expandaroundcenter(char *s, int left, int right)
{
int L = left, R = right;
while (L >= 0 && R < strlen(s) && s[L] == s[R]) {
L--;
R++;
}
return R - L - 1;
}