LeetCode - 5. Longest Palindromic Substring - C++

最长回文子字符串。

借鉴做过的 47. Palindromic Substrings ,写出如下:

class Solution {
public:
    string longestPalindrome(string s) {
        int length = s.size();
        int current = 0;
        int maxLength = 0;
        int left = 0;
        for(int i=0; i<length; i++) {
            current = basePivot(s, length, i, i);
            if(current > maxLength) {
                maxLength = current;
                left = i-current/2;
            }
            
            current = basePivot(s, length, i, i+1);
            if(current > maxLength) {
                maxLength = current;
                left = i - current/2 + 1;
            }
        }
        
        string result(s.substr(left, maxLength));
        return result;
    }
    
    int basePivot(string s, int length, int left, int right) {
        int start = left, end = right;
        while(left>=0 && right<length && s[left] ==s[right]) {
            start--;
            end++;
        }
        return end-start-1;
    }
};

第一次提交没过,没过的case是空字符串。改了改各变量初始值后通过。

这个代码不是最精简,但是还算明了

另外:

1.子字符串用substr(start, length) 

todo:

2.Soution中的第 1 种方法: 找最大共有子字符串 + 判断位置,有空可以看看

3.Solution中第 3 种方法用动态规划,应该是弄一个二维数组记录[row,col]字符串是不是回文,没仔细看。

4.Solution中第 5 种方法 Manacher's Algorithm 第二次见了,第一次在 47. Palindromic Substrings Solution里,讲的比较详细。应该学学,但是不要求。

猜你喜欢

转载自blog.csdn.net/L_bic/article/details/89175905