--

leetcode 005: longest palindromic substring



https://leetcode.com/problems/longest-palindromic-substring/



problem:
  
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"



start code (c++)
class Solution {
public:
    string longestPalindrome(string s) {
        
    }
};



solution 1:

我的思路:
如果我们取查找 从第 N 个字符开始的回文字符串,是非常困难的。
所以我们换个思路,利用潜在的回文字符串的中间位置开始遍历。
我们查找以字符 N 为回文字符串中间值的最大串,从左到右遍历 N,找到最大的回文字符串。


class Solution {
public:
    string longestPalindrome(string s) {
        if (s.size() <=1)
            return s;
        int longestSiz = 1;
        int longestBeg = 0;
        int longestEnd = 0;
        for (int i = 0; i < s.size() -1; i ++){
            
            # consider the palindromic sub string using s[i] as the center
            int j = 1;
            while ((i -j) >=0 && (i + j) < s.size()){
                if (s[i -j] == s[i +j])
                    j ++;
                else
                    break;
            }
            int localLongestSiz = 1 + 2 * (j -1);
            int localLongestBeg = i - j +1;
            int localLongestEnd = i + j -1;
            if (localLongestSiz > longestSiz){
                longestSiz = localLongestSiz;
                longestBeg = localLongestBeg;
                longestEnd = localLongestEnd;
            }
            
            # consider the palindromic sub string has even characters and s[i] is the on the left half ner the middle
            if (s[i] == s[i+1]){
                j = 1;
                while ( (i-j) >= 0 && (j+1 + j) < s.size()){
                    if (s[i -j] == s[i +1 + j])
                        j ++;
                    else
                        break;
                }
                localLongestSiz = 2 * j;
                localLongestBeg = i - j + 1;
                localLongestEnd = i + 1 + j -1;
                if (localLongestSiz > longestSiz){
                    longestSiz = localLongestSiz;
                    longestBeg = localLongestBeg;
                    longestEnd = localLongestEnd;
                }
            }
        }
        return s.substr(longestBeg, longestSiz);
        
    }
};