1. 程式人生 > >LeetCode:5. Longest Palindromic Substring(Week 3)

LeetCode:5. Longest Palindromic Substring(Week 3)

5. 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
      	Input: "babad"
      	Output: "bab"
      	Note: "aba" is also a valid answer.
      
  • 解題思路

    • 這道題要求我們找出一個字串裡面的最長迴文串,而什麼是迴文串呢,迴文串就是正反讀都是一樣的字串。對於這個問題,解決方法就是找一個字元,以其為中心,向兩邊擴充套件尋找出最長的迴文串,該演算法的時間複雜度為O
      (n)O(n)
      ,當然還需要注意一點的就是迴文串的長度可奇可偶,如長度為奇數的迴文串"aba"以及長度為偶數的迴文串"baab",因此在以某個字元為中心的向兩邊擴充套件的需要額外的考慮。
  • 實現程式碼

    class Solution {
    public:
        string longestPalindrome(string s) {
        	if(s.size() <= 1)	return s;
           int len = 0;
           int id = 0;
           for(int i = 0; i < s.size() - 1; ++i) {
           		if(s[i] == s[i+1]) 
           			searchLongestPalindrome(i, i+1, id, len, s);
           		searchLongestPalindrome(i, i, id, len, s);
           } 
           return s.substr(id, len);
        }
    
        void searchLongestPalindrome(int left, int right, int &id, int &len, string s) {
        	while(left >= 0 && right < s.size() && s[left] == s[right]) {
        		--left;
        		++right;
        	}
        	int tmp = right - left - 1;
        	if(tmp >= len) {
        		id = left + 1;
        		len = tmp;
        	}
        }
    };