標籤:
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.
題目描述很簡單,就是尋找一個字串的最大迴文。
1.暴力搜尋
窮舉所有的可能,演算法複雜度是O(n^3);
2.dp求解
http://articles.leetcode.com/2011/11/longest-palindromic-substring-part-i.html
3.對稱
這裡考慮到每個迴文單詞都是對稱的,所以這裡可以使用對稱的思想進行解答。分別遍曆以每個字母為中心的迴文字元的最大長度,演算法複雜度為O(n ^ 2);空間複雜度是
O(1);
1 class Solution { 2 public: 3 string expand(string&s, int l, int h) 4 { 5 while((l >= 0) && (h < s.size()) && (s[l] == s[h])) 6 { 7 l--; h++; 8 } 9 10 return s.substr(l+1, h-1-l);11 }12 13 string longestPalindrome(string s) {14 string res = s.substr(0,1);15 16 for(int i = 0; i < s.size(); i++)17 {18 string p;19 p = expand(s, i, i);20 21 if(p.size() > res.size())22 res = p;23 p = expand(s, i, i+1);24 25 if(p.size() > res.size())26 res = p;27 }28 29 return res;30 }31 };
4。Manacher’s Algorithm
http://www.felix021.com/blog/read.php?2040
http://articles.leetcode.com/2011/11/longest-palindromic-substring-part-ii.html
Longest Palindromic Substring