【medium】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"

class Solution {
public:
    string longestPalindrome(string s) {
        string str = "", ans = "";
        int maxl = -1;
        int cnt;
        
        # 如果插入特殊符号,就不用考虑奇回文或者偶回文
        int len = s.length();
        for (int i=0; i<len; i++){
            str += '#';
            str += s[i];
        }
        str += '#';
        
        for (int i=1; i<2*len; i++){ //遍历中心节点,左右扩展,查找回文
            cnt = 0; // wrong
            while ((i-cnt>=0) && (i+cnt<=2*len) && (str[i-cnt]==str[i+cnt])) // str
                cnt ++;
            cnt --;  // wrong
            if (cnt > maxl){
                maxl = cnt;
                ans = s.substr((i-cnt)/2, (i+cnt)/2-(i-cnt)/2); // wrong
            }
        }
        
        return ans;
        
    }
};

 

posted @ 2019-05-01 03:09  Sherry_Yang  阅读(115)  评论(0编辑  收藏  举报