【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.spa

Example 1:code

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

Example 2:blog

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;
        
    }
};
相關文章
相關標籤/搜索