[Leetcode]Longest Palindromic Substring
阿新 • • 發佈:2018-01-20
回文 uri .com art code 奇數 sub 字符串 als
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,因此可以對字符串中的每一個元素,同時向左和向右探測,直到回文子串結束,每次判斷得到的子串是否是最長的即可。
[Leetcode]Longest Palindromic Substring