Leecode Week4: Longest Palindromic Substring

Week4:Longest Palindromic Substring

Difficulty:Medium

1.Question

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.


Input: “cbbd”

Output: “bb”

2.Algorithm

使用動態規劃求解:

P(i,j)=true,"SiSj"false

P(i,j)=(P(i+1,j1)andSi==Sj)

P(i,i)=trueP(i,i+1)=(Si==Si+1)

3.Solution

class Solution {
public:
    string longestPalindrome(string s) {
        int start = 0;
        int maxLength = 0;
        for(int i = 0; i < s.length(); i++) {
            //以i爲中心,返回長度必定爲奇數
            int len1 = maxAroundCenter(s,i,i);
            //以i和i+1爲中心,返回長度必定爲偶數
            int len2 = maxAroundCenter(s,i,i+1);
            //以i爲中心的最大回文子串長度
            int len = 0;
            if(len1 < len2 ) {
                len = len2;
            } 
            else {
                len = len1;
            }
            if(maxLength < len) {
                maxLength = len;
                start = i - (len-1) / 2;
            }
        }
        return s.substr(start,maxLength);
    }
    int maxAroundCenter(string s, int left, int right) {
        while(left >= 0 && right < s.length() && s[left] == s[right]) {
            left--;
            right++;
        }
        return right - left - 1;
    }
};
發佈了25 篇原創文章 · 獲贊 0 · 訪問量 1634
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章