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”

Subscribe to see which companies asked this question

即求最长回文子串。什么是回文?就是你从左边读和从右边读是一样一样的。
基本思路是遍历字符串,对每个字符进行一个expand操作,即分别对每个字符进行向两侧扩展,扩展的条件就是两侧的字符需要相同。这样,如果是回文,就能一直向两侧扩展开来,记算下回文长度即可。

class Solution {
public:
    string longestPalindrome(string s) {
        int start = 0, end = 0;
        int len1, len2, len;
        for(int i = 0; i < s.length(); ++i)
        {
        //分别对当前字符和后一个字符进行expand,因为有两种回文:aba和abba
            len1 = ExpandString(s, i, i);
            len2 = ExpandString(s, i, i+1);
            len = max(len1,len2);
            //计算回文的位置
            if(len > end - start + 1)
            {
                start = i - (len - 1)/2;
                end = i + len/2;
            }
        }
        return s.substr(start, end - start + 1);
    }
    //向两侧expand
    int ExpandString(string s, int left, int right)
    {
        int l = left, r = right;
        //如果s[l] == s[r]相同则条件通过,符合回文属性
        while(l >= 0 && r < s.length() && s[l] == s[r])
        {
            l--;
            r++;
        }
        return r-l-1;
    }
};

你可能感兴趣的:(leetcode,leetcode)