最長迴文子串問題(C C++及Java實現)

問題:給定一個字符串,設計算法找到它的最長迴文子串的長度。如 “BBABCBCAB”,它的最長迴文子串爲 “BABCBAB”,長度爲 7。“BBBBB” 和 “BBCBB” 也是迴文子串,但是它們的長度不是最長的。

分析:顯然如果用窮舉法是可以的,但是對這個問題用窮舉法,算法複雜度是指數級的。所以我們考慮動態規劃算法。

1)最優子結構性質:假設輸入的 n 個字符爲 X[0..n-1],L(0, n-1) 爲 X[0..n-1] 的最長迴文子串的長度;如果第一個和最後一個字符相同,那麼有 L(0, n-1) = L(1, n-2) + 2 否則 Else L(0, n-1) = MAX (L(1, n-1), L(0, n-2))。顯然這是個遞歸公式,所以我們有如下的遞歸算法

// Everay single character is a palindrom of length 1
L(i, i) = 1 for all indexes i in given sequence

// IF first and last characters are not same
If (X[i] != X[j])  L(i, j) =  max{L(i + 1, j),L(i, j - 1)} 

// If there are only 2 characters and both are same
Else if (j == i + 1) L(i, j) = 2  

// If there are more than two characters, and first and last 
// characters are same
Else L(i, j) =  L(i + 1, j - 1) + 2 

2)重疊的子問題

基於上面的遞歸算法,我們用 C 語言實現如下

#include<stdio.h>
#include<string.h>
 
// A utility function to get max of two integers
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章