Longest Palindromic Substring 题解
原创文章,拒绝转载
题目来源:https://leetcode.com/problems/longest-palindromic-substring/description/
Description
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Input: "cbbd"
Output: "bb"
Solution
class Solution {
private:
int resStart;
int resSize;
int inSize;
void expandPalindrome(string& s, int start, int end) {
while (start >= 0 && end < inSize && s[start] == s[end]) {
start--;
end++;
}
start++;
int temp = end - start;
if (temp > resSize) {
resSize = temp;
resStart = start;
}
}
public:
string longestPalindrome(string s) {
inSize = s.length();
if (inSize <= 1)
return s;
resStart = resSize = 0;
for (int i = 0; i < inSize - 1; i++) {
expandPalindrome(s, i, i); // 求奇数长度的回文子串
expandPalindrome(s, i, i + 1); // 求偶数长度的回文子串
}
return s.substr(resStart, resSize);
}
};
解题描述
这道题考察的是求一个字符串中的最长回文子串。而对每一个非空的输入串来说,其回文子串最短为1,因此可以对字符串中的每一个元素,同时向左和向右探测,直到回文子串结束,每次判断得到的子串是否是最长的即可。