5. Longest Palindromic Substring
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.Example:
Input: "cbbd" Output: "bb"
本题无他法,唯有蛮力而已。注意怎样组织代码,里面的门道很多。在这个上面吃了很多亏。
另外要注意的是,本题中或者类似的题,判断是不是palindromic substring的方法都是从字符串的中间出发,向两端扩展,判断字符是否对称。
class Solution { public: string longestPalindrome(string s) { int n = s.size(); if (n <= 1) return s; int maxlen = 0, bestStart = 0; for (int i = 0; i <= n-1; ++i) { int curlen = 0; if (i <= n - 2) { if (s[i] == s[i+1]) { curlen = isPalindrome(s, i, i+1); } if (curlen > maxlen) { maxlen = curlen; bestStart = i + 1 - maxlen/2; } } curlen = isPalindrome(s, i, i); if (curlen > maxlen) { maxlen = curlen; bestStart = i - (maxlen - 1) / 2; } } return s.substr(bestStart, maxlen); } private: int isPalindrome(const string& s, int pos1, int pos2) { int n = s.size(); while (pos1 >= 1 && pos2 <= n-2) { if (s[pos1 - 1] == s[pos2 + 1]) { --pos1; ++pos2; } else { break; } } int len = pos2 - pos1 + 1; return len; } };
浙公网安备 33010602011771号