[leetcode]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, and there exists one unique longest palindromic substring.
分析一:
最直观思路是枚举法,通过对每个字符为中心,中间向两边展开,注意‘aba'和‘aa’这种情况,长度为奇数的回文字符串,它沿着中心字符轴对称,对于长度为偶数的回文字符串,它沿着中心的空字符轴对称。时间复杂度为O(N^2).
//从中间向两边展开 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 longestPalindromeSimple(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; }
分析二:
利用动态规划:f(i,j)表示区间[i,j]是否为回文字符串,其状态转移方程为:
该方程含义:对于对角线的元素,f(i,j)为true,对于相邻的元素,i和j=i+1,如果s(i)=s(j),则f(i,j)为回文字符串;对于非相邻的i,j,如果s(i)=s(j)同时(i+1,j-1)子字符串为回文字符串,则f(i,j)为回文字符串,否则false。
// 时间复杂度 O(n^2)空间复杂度O(n^2) class Solution { public: string longestPalindrome(const string& s) { const int n = s.size(); bool f[n][n]; fill_n(&f[0][0], n * n, false); size_t max_len = 1, start = 0; // 回文长度 for (size_t i = 0; i < s.size(); i++) { f[i][i] = true; for (size_t j = 0; j < i; j++) { // [j, i] f[j][i] = (s[j] == s[i] && (i - j < 2 || f[j + 1][i - 1]));//判断f[j][i]是否是回文字符
if (f[j][i] && max_len < (i - j + 1)) {
max_len = i - j + 1;
start = j;
}
}
}
return s.substr(start, max_len);
}
};
当然,效率最高的是经典的manacher算法,复杂度O(n),但是用的不多,老是忘掉。
参考:
http://blog.csdn.net/feliciafay/article/details/16984031;
http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html