1. 程式人生 > 實用技巧 >647. 迴文子串 (馬拉車演算法)- 8月19日

647. 迴文子串 (馬拉車演算法)- 8月19日

題目

647. 迴文子串

我的思路

設兩個指標,遍歷兩個指標之間形成的字串?複雜度n*n*n如何優化
第一次遍歷設定一個指標,從頭到尾掃描。該指標作為可能是迴文串的子串的最中間字元。一次判斷該指標兩側的字元是否匹配,若匹配則計數並繼續判斷更外側的字元 第二次遍歷設定兩個指標,兩個指標始終相鄰,也從頭到尾掃描字串。若兩個指標指向的字元匹配,那麼繼續判斷兩側的字元是否匹配並計數,直到不匹配或者達到字串邊界 n*n的複雜度

我的實現

class Solution {
public:
    int countSubstrings(string s) {
        int left,right;
        
int pos1 = 0; int maxPos = s.size()-1; int count = 0; while(pos1<=maxPos){ left = pos1-1; right = pos1+1; count++; while(left>=0&&right<=maxPos){ if(s[left]==s[right]){ count++; left
--; right++; }else{ break; } } pos1++; } pos1=0; while(pos1<maxPos){ left = pos1; right = pos1+1; while(left>=0&&right<=maxPos){
if(s[left]==s[right]){ count++; left--; right++; }else{ break; } } pos1++; } return count; } };

拓展學習

馬拉車演算法可以把時間複雜度降到On

核心思想:

首先可以在源字串的所有字元之間插入一個特殊字元,這樣,偶數或奇數長度的迴文子串都對應一個奇數長度的迴文串,方便計算。

在對依次每一個字元進行中心拓展時,其實可以利用迴文串的特點減少累贅計算。如果當前字元處於此前發現過的迴文子串中,那麼以當前字元為中心發現迴文子串不必從當前字元兩側相鄰的字元開始,由於對稱性,至少可以從此前已發現的那個包含當前字元的迴文串的右邊界作為當前字元為中心的字串的右邊界開始匹配。

這樣的話,需要藉助輔助空間儲存已經訪問的字元的以它為中心的最大回文串長度。以空間換時間,需要On的空間複雜度,時間複雜度降到了On。

class Solution {
public:
    int countSubstrings(string s) {
        int n = s.size();
        string t = "$#";
        for (const char &c: s) {
            t += c;
            t += '#';
        }
        n = t.size();
        t += '!';

        auto f = vector <int> (n);
        int iMax = 0, rMax = 0, ans = 0;
        for (int i = 1; i < n; ++i) {
            // 初始化 f[i]
            f[i] = (i <= rMax) ? min(rMax - i + 1, f[2 * iMax - i]) : 1;
            // 中心拓展
            while (t[i + f[i]] == t[i - f[i]]) ++f[i];
            // 動態維護 iMax 和 rMax
            if (i + f[i] - 1 > rMax) {
                iMax = i;
                rMax = i + f[i] - 1;
            }
            // 統計答案, 當前貢獻為 (f[i] - 1) / 2 上取整
            ans += (f[i] / 2);
        }

        return ans;
    }
};

作者:LeetCode-Solution
連結:https://leetcode-cn.com/problems/palindromic-substrings/solution/hui-wen-zi-chuan-by-leetcode-solution/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。