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" 自己写的
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"
自己写的代码是用滑动窗口配合std::map构建的词典进行暴力检测,但是这样实在是太丑了,于是参考网上给的Java解法写了一个更漂亮的写法,不过这种算法虽然思路清晰简洁,运行速度却并不快(54%),神奇:)
这种算法的基本思想是,如果已有一个回文字符串,并且这个回文字符串左右侧的临近字符相同,那么新的回文字符串可以通过向左向右各扩展一位得到。需要注意的是,扩展字符串的时候,其起始点既包含每个字符,也包含每个相邻字符的中间位置(比如 “abba”的起始扩展就应该在第二与第三个字符之间)。最终通过的代码如下:
class Solution { public: string longestPalindrome(string s) { if(s.length()<=1) return s; int start = 0; int maxLen = 0; for(int center=0;center<s.length();center++) { int len1,len2; len1 = expandAroundCenter(s,center,center); if((center+1)==s.length()) len2 = 1; else len2 = expandAroundCenter(s,center,center+1); int len = (len1 > len2)? len1:len2; if(len > maxLen) { maxLen = len; start = center - (len-1)/2; } } return s.substr(start,maxLen); } int expandAroundCenter(string s, int L, int R) { int len; while(L>=0&&R<s.length()) { if(s[L] == s[R]) { len = R - L + 1; L--; R++; } else break; } return len; } };