1. 程式人生 > >【LeetCode & 劍指offer刷題】字串題13:Longest Palindromic Substring

【LeetCode & 劍指offer刷題】字串題13:Longest Palindromic Substring

【LeetCode & 劍指offer 刷題筆記】目錄(持續更新中...)

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. Example 1:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: "cbbd" Output: "bb"
C++
  //問題:最長迴文子串 //方法一:O(n^2),O(1) class Solution { private :     int start,maxlen; //類的成員變數 public : string longestPalindrome ( string s )    
{         int len = s . size ();         if ( len < 2 ) return s ;                 start = maxlen = 0 ; //成員變數初始化(一般在建構函式裡通過初始化列表初始化,這裡僅為解題方便)         for ( int i = 0 ; i < len ; i ++) //掃描字串,掃描到的字元作為迴文的中心字元         {             extendPalindrome ( s , i , i ); //假定奇數長度的子串,從中心擴充套件迴文             extendPalindrome ( s , i , i + 1 ); //假定偶數長度的子串,從中心兩個元素擴充套件迴文         }       //  cout<<start<<" "<<maxlen<<endl;         return s . substr ( start , maxlen ); //注意:substr(pos, count)返回含子串 [pos, pos+count) 的 string     }     private :     void extendPalindrome ( string & s , int left , int right )     {         while ( left >= 0 && right < s . size () && s [ left ] == s [ right ]) //由中心向兩邊擴充套件(問題valid Palindrome中為從兩邊開始向中間掃描         {             left --;             right ++;         } //迴圈結束後,left和right分別指向實際區間左右各偏一個長度的位置         if ( right - left - 1 > maxlen ) //通過成員變數在成員函式之間傳值          {             start = left + 1 ; //更新起始點             maxlen = right - left - 1 ; //更新最大長度         }     } };   //方法二: Manacher's Algorithm  O(n)