Longest Palindromic Substring

來源:互聯網
上載者:User

標籤:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.