Longest Palindromic Substring--LeetCode

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.

Example:

Input: "cbbd"

Output: "bb"

Solution:

找一個字符串的迴文子串,可以遍歷這個字符串,然後從一個字符向左右兩邊展開,檢查是否對稱,注意要分清奇數個數的對稱和偶數個數的對稱。然後從中找到最長的迴文子串,時間複雜度爲O(N^2)。
class Solution {
public:
    string longestPalindrome(string s) {
        string answer = "";
        int maxlength = 0;
        int length = s.length();
        for(int a = 0; a < length; a++)
        {
            int b = 0;
            //奇數的對稱
            while(a - b >= 0 && a + b < length && s[a - b] == s[a + b])
            {
                b++;
            }
            int c = 0;
            //偶數的對稱
            while(a - c >= 0 && a + c + 1 < length && s[a - c] == s[a + c + 1])
            {
                c++;
            }
            if(2 * b-1 > maxlength)
            {
                maxlength = 2 * b - 1;
                answer = s.substr(a-b+1, 2*b-1);
            }
            if(2 * c > maxlength)
            {
                maxlength = 2 * c;
                answer = s.substr(a-c+1, 2*c);
            }
        }
        return answer;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章