[C++] 最长回文子串

二、代码

class Solution {		
public:
    string longestPalindrome(string s) {	// 非动态规划方法
        int left, right, len, stmaxlen, stmaxleft;
        string ans;     // 最长回文子串
        left = 0;       // 左指针
        right = 0;      // 右指针
        len = s.size(); // 给定字符串长度
        stmaxlen = 0;   // 最长回文子串长度
        stmaxleft = 0;  // 最长回文子串的左指针

        for(int i = 0; i < len; ++i){
            int stlen;		// 当前回文子串长度
            left = i - 1;	// 左指针
            right = i + 1;	// 右指针

            while(left >= 0 && s[left] == s[i]){    // 左边有相同元素
                --left;
            }

            while(right < len && s[right] == s[i]){     // 右边有相同元素
                ++right;
            }

            while(left >= 0 && right < len && s[right] == s[left]){ // 左右相等
                --left;
                ++right;
            }

            stlen = right - left - 1;   // 当前回文子串的长度

            if(stlen > stmaxlen){ // 判断是否为最长回文子串
                stmaxleft = left + 1;
                stmaxlen = stlen;
            }
        }

        for(int i = stmaxleft; i < stmaxleft + stmaxlen; ++i){  // 获得最长回文子串
            ans += s[i];
        }
        return ans;
    }
};

版权声明:本文为a1651950431原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。