Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
基本思路:回文字符串显然有个特征是沿着中心那个字符轴对称。比如aha沿着中间的h轴对称,a沿着中间的a轴对称。那么aa呢?沿着中间的空字符‘‘轴对称。所以对于长度为奇数的回文字符串,它沿着中心字符轴对称,对于长度为偶数的回文字符串,它沿着中心的空字符轴对称。对于长度为N的候选字符串,我们需要在每一个可能的中心点进行检测以判断是否构成回文字符串,这样的中心点一共有2N-1个(2N-1=N-1
+ N)。
检测的具体办法是,从中心开始向两端展开,观察两端的字符是否相同。代码如下:
class Solution { public: string expandAroundCenter(string s, int c1, int c2) { int l = c1, r = c2; int n = s.length(); while (l >= 0 && r <= n-1 && s[l] == s[r]) { l--; r++; } return s.substr(l+1, r-l-1); } string longestPalindrome(string s) { int n = s.length(); if (n == 0) return ""; string longest = s.substr(0, 1); // a single char itself is a palindrome for (int i = 0; i <= n-1; i++) { string p1 = expandAroundCenter(s, i, i); //长度为奇数的候选回文字符串 if (p1.length() > longest.length()) longest = p1; string p2 = expandAroundCenter(s, i, i+1);//长度为偶数的候选回文字符串 if (p2.length() > longest.length()) longest = p2; } return longest; } };
http://articles.leetcode.com/2011/11/longest-palindromic-substring-part-ii.html
Leetcode:Longest Palindromic Substring
原文地址:http://blog.csdn.net/wolongdede/article/details/45288391