1.题目链接
https://leetcode-cn.com/problems/longest-palindromic-substring/
2.题目描述
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
示例 1:
输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。
示例 2:
输入: "cbbd"
输出: "bb"
3.题目解析
回文串指的是,从左往右和从右往左读是一样的,题目要求找到最长的回文子串,从当前字符往右读取连续重复字符,即为子串的中心,并向左右读取,判断当前子串是否为回文子串。
4.代码实现
char * longestPalindrome(char * s){ int left = 0; int right = 0; int maxlen = 0; int k = 0; int start = 0; while (s[k]) { right = k; left = k - 1; while (s[right] == s[k]) { right++; } k = right; while (left >= 0 && s[left] && s[left] == s[right]) { left--; right++; } if (right - left - 1 > maxlen) { start = left + 1; maxlen = right - left - 1; } } char* returnStr = (char*)malloc(maxlen + 1); returnStr[maxlen] = '