问题描述:
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. (找字符串中的最长回文)
原题地址:https://leetcode.com/problems/longest-palindromic-substring/
本题通过动态规划来解决。分两种情况,第一种情况为从一个字符开始往外扩展判断最长的回文,第二种情况为从两个相邻的字符开始往外扩展判断最长的回文。从中心扩展通过一个单独的函数expanAroundCenter来实现。该算法时间复杂度为O(n^2)。
class Solution { public: string longestPalindrome(string s) { int n = s.length(); if (n == 0) return ""; // a single char itself is a palindrome string longest = s.substr(0, 1); 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; } //从中心开始判断是否为回文 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); } };