最長迴文子串(C/C++)__C++

來源:互聯網
上載者:User

給定一個字串,求它的最長迴文子串的長度。

思路:從給定字串的頭部開始,在每個字元的位置處設定兩個指標,分別向前和向後兩個方向依次判斷各字元是否相等,當兩個指標指向的字元不相等時計算迴文子串的長度。重複這樣的過程,直至掃描到字串的最後一個字元為止。

內層的兩個 for 迴圈,它們分別對於以 i 為中心的,長度為奇數和偶數的兩種情況,整個代碼遍曆中心位置 i 並以之擴充,找出最長的迴文。

注意:迴文子串長度的計算方法

代碼如下:

//最長迴文子串#include <iostream>using namespace std;//*s為字串,n為字串的長度int LagPalindrome(char *str, int n){int count = 0;int max = 0;//最長迴文子串的長度if (str == NULL || n<1){return 0;}for (int i = 0; i < n; i++){//子串為奇數時for (int j = 0; (i-j)>=0&&(i+j)<n; j++){if (str[i - j] != str[i + j]){break;}count = 2 * j + 1;}if (count > max){max = count;}//子串為偶數時for (int k = 0; (i - k)>=0 && (i + k + 1) < n; k++){if (str[i - k] != str[i + k+1]){break;}count=2*k + 2;}if (count > max){max =count ;}}return max;}int main( ){char str[] = "abccba";int n = strlen(str);int MaxLen;MaxLen = LagPalindrome(str, n);cout << "最長迴文子串的長度是:"<<MaxLen<<endl;return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.