当前位置 : 主页 > 手机开发 > ROM >

【medium】5. Longest Palindromic Substring 最长回文子串

来源:互联网 收集:自由互联 发布时间:2021-06-10
Given a strings, find the longest palindromic substring ins. You may assume that the maximum length ofsis 1000. Example 1: Input: "babad"Output: "bab"Note: "aba" is also a valid answer. Example 2: Input: "cbbd"Output: "bb" class Solution {

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;
        
    }
};
网友评论