5. 最长回文子串(c++)

c++:

class Solution {
public:
    string longestPalindrome(string s) {
        int n = s.size();
        int i, j;
        int leng_max = 0;
        string max;
        if(n < 1)
            return s.substr(0,0);
        
        for(i = 0; i < n; i++){
            
            for(j = 0; (i - j >= 0)&&(i + j < n); j++){
                if(s[i - j] != s[i + j])
                    break;
                if(2 * j + 1 > leng_max){
                    max = s.substr(i - j, i + j);
                    leng_max += 1;    
                }
            if(i + 1 < n){
                for(j = 0; (i - j >= 0)&&(i + j + 1 < n); j++){
                    if(s[i - j] != s[i + j + 1])
                        break;
                    if(2 * j + 2 > leng_max){
                        max = s.substr(i - j, i + j + 1);
                        leng_max += 1;
                    }
                }
            }
        }
        return max;
    }
    };

猜你喜欢

转载自blog.csdn.net/weixin_42158523/article/details/85247075