LeetCode Problem No.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 1

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2

Input: "cbbd"
Output: "bb"

Solution

//遍历每个字符,两边寻找相等的字符,确定最大的回文串即可
//注意遍历时需要考虑相对称(aa)和中心对称(aba)两种情况
class Solution {
public:
    string longestPalindrome(string s) {
        if(s.length()<1)
        {
            return "";
        }
        int l = 0;
        int r = 0;
        for(int i = 0; i < s.length(); i++)
        {
            int l1 = maxsub(s, i, i);
            int l2 = maxsub(s, i, i+1);
            int max = l1 > l2 ? l1 : l2;
            if(max>r-l)
            {
                l = i-(max-1)/2;
                r = i+max/2;
            }
        }
        
        return s.substr(l,r-l+1);
    }
    
    int maxsub(string s, int left, int right)
    {
        int l = left;
        int r = right;
        while(l>=0&&r

你可能感兴趣的:(LeetCode Problem No.5)